Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 438
nora Avatar asked Apr 06 '17 17:04

nora


People also ask

Can you use backticks in JSON?

Please note that a JSON-encoded object has several important differences from the object literal: Strings use double quotes. No single quotes or backticks in JSON.

How use fetch and display JSON data in HTML using JavaScript?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

Is JSON Parsable JavaScript?

JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.


2 Answers

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'
like image 125
Manasvi Sareen Avatar answered Sep 23 '22 17:09

Manasvi Sareen


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

const data = 'some value';
JSON.stringify({
  data,
});
// expected: "{\"data\": \"some value\"}"
like image 45
ElPepe Avatar answered Sep 20 '22 17:09

ElPepe