Javascript: How to use Template Literals with JSON?

时间:2017-04-06 17:16:31

标签: javascript json template-literals

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 JSON.parse() which doesn't support ` instead of ", so it seems one can't save Template Literals directly in the files.

Goal: To use this for dynamic strings and translation and to get rid of confusing stuff like ("Hello " + username + "! How are you?") which requires multiple strings to be stored for just one message, and instead save my stuff beautifully and simple as

`Hello, ${username}! How are you?`

where username points to the dynamic variable with the same name. Is that possible? If yes, how to achieve this? It's okay if i have to use a function to somehow convert the strings into Template Literals as long as it doesn't hit hard on the overall performance, but I would like to at least avoid eval.

3 个答案:

答案 0 :(得分:2)

您始终可以使用JSON.stringify来包含动态数据:

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

答案 1 :(得分:0)

您可以创建自己的函数来解析模板文字

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'

答案 2 :(得分:-1)

我发现将问题分为几个JSON子字符串更容易。创建键“消息”,此键存储部分消息。它还适用于i18n。

Books

然后,在解码后,您可以像访问 myNewView.insertSubview(myWhiteViewWithBorder, at: 0) myNewView.insertSubview(myGreenView, at: 1)