Skip to content Skip to sidebar Skip to footer

Javascript: How To Use Template Literals With JSON?

I discovered Javascript ES6 Template Literals today. Just one word: Awesome! Question: How to store and load Template Literals as JSON? I load some files via XHR, followed by some

Solution 1:

You can create your own function to parse template literal,

function stringTemplateParser(expression, valueObj) {
  const templateMatcher = /{{\s?([^{}\s]*)\s?}}/g;
  let text = expression.replace(templateMatcher, (substring, value, index) => {
    value = valueObj[value];
    return value;
  });
  return text
}

console.log(stringTemplateParser('my name is {{name}} and age is {{age}}', {name: 'Tom', age:100}));


// output 'my name is Tom and age is 100'

Solution 2:

You could always use JSON.stringify to enclose dynamic data:

const data = 'some value';
JSON.stringify({
  data,
});
// expected: "{\"data\": \"some value\"}"

Solution 3:

I found it easier to separate the problem in a few substrings of JSON. Create the key "message" and this key stores parts of the message. It also works well for i18n.

{
  "message" : {
    "_0": "first part ",
    "_1": "after first variable. ",
    "_2": "after another variable"
  }
}

And then, after decoding it, you can access it like ${message._0}${variable}${message._1}${var2}${message._2}


Solution 4:

Try json-templates. Looks like exactly what you're looking for.


Post a Comment for "Javascript: How To Use Template Literals With JSON?"