I have a placeholder object named ${var_name}
{
"name": "${title}",
"description": "${description}",
"provider": {
"@type": "Organization"
},
"hasInstance": [
{
"@type": "instance",
"mode": [
"study",
"online"
],
"offers": {
"@type": "Offer",
"price": "${price}"
}
}
]
}
And I also have a substitutions object
{
"title": "aaa",
"description": "bbb \n ccc",
"price": 100,
"history": "ddd"
}
Once the placeholders are replaced, the result should be:
{
"name": "aaa",
"description": "bbb \n cc",
"provider": {
"@type": "Organization"
},
"hasInstance": [
{
"@type": "instance",
"mode": [
"study",
"online"
],
"offers": {
"@type": "Offer",
"price": 100
}
}
]
}
Here is the function with the following steps:
- convert the object with placeholders to a string
- then replace with the substitutions object
- convert the string back to an object
The issue is: JSON.parse
will fail with data that contains JSON escape characters like: ", \, /, \b, \f, \n, \r, \t
function replace(template, data) {
let templateString = JSON.stringify(template);
var placeholders = templateString.match(/\${([\w\.\:]+)}/g);
placeholders.forEach(placeholder => {
// convert ${var_name} to var_name, then assign to phText
let phText = placeholder.substring(2,placeholder.length - 1);
if(data[phText]) {
templateString = templateString.replace(placeholder, data[phText]);
}
});
return JSON.parse(templateString);
}