问题
I know, I don't need it, but I think I actually do.
I want to have a valid JS code rendered by handlebarsjs before it is even rendered. The JS minification tools just minify valid JS files and minifying on the fly increases processing time. This is the JS handlebars code.
var stringsObj = JSON.parse('{{{ json stringsDataObj }}}');
As you see, the single quotes up-there make that line of code a valid JS code. The handlebars helper is:
function json(context) {
return JSON.stringify(context);
}
And what's the problem? Well, some of the items in stringObj happen to have single quotes
stringsDataObj = {
"str1": "I'm here",
"str2": "You're there"
}
and when it rendes
var stringsObj = JSON.parse('"str1": "I'm here", "str2": "You're there"');
gives an JS error
Is there a way to escape also single quotes in JSON.stringify? I tried with a replacer function, but without success.
回答1:
What should actually be rendered here is:
var stringsObj = JSON.parse('{"str1": "I'm here", "str2": "You're there"}');
JSON is valid Javascript code, it's syntactically a subset of Javascript. Which means JSON.stringify is outputting a valid Javascript literal. You don't actually need to go through the complications of generating JSON and then ensuring it's a valid Javascript string literal which you then parse with JSON.parse. You just do:
var stringsObj = {{{ json stringsDataObj }}};
Which renders:
var stringsObj = {"str1": "I'm here", "str2": "You're there"};
Which is a valid Javascript object literal.
回答2:
I solved my issue with the following helper
function json(context) {
return JSON.stringify(context).replace(/[\/\(\)\']/g, "\\$&");
}
I.e., the escape must be done after the stringification.
来源:https://stackoverflow.com/questions/48378985/escape-single-quotes-in-json-stringify