Escape single quotes in JSON.stringify

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.

Upvotes: 5

Views: 18489

Answers (3)

Yaw
Yaw

Reputation: 176

This should get the single quote to be displayed in the browser:

var final_string = JSON.stringify(context).replace(/[\/\(\)\']/g, "'");

Upvotes: 11

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.

Upvotes: 4

deceze
deceze

Reputation: 522500

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.

Upvotes: -1

Related Questions