Let's say I have:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
var greetings = 'hello';
how to evaluate template to get hello ?
Let's say I have:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
var greetings = 'hello';
how to evaluate template to get hello ?
Since JSON.parse()
returns obj.greetings
as string, you can use eval()
to run the string as js. So just:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = eval(obj.greetings); //`${greetings}`
var greetings = 'hello';
console.log(greetings)// hello
But eval()
should always be used with caution as string maybe entered through user input.
Edit:
The above code with eval
returns undefined
.
This is because JavaScript Hoisting doesn't work for initialized variable.
So we surely need to move the initialisation var greetings = 'hello';
at the top.
Solution without eval()
:
Apply template string to the whole string.
var greetings = 'hello';
var json = `{"greetings": "${greetings}"}`;
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
console.log(template); //hello