Escape single quotes in JSON.stringify

12,575

Solution 1

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

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

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

Share:
12,575
João Pimentel Ferreira
Author by

João Pimentel Ferreira

Updated on June 04, 2022

Comments

  • João Pimentel Ferreira
    João Pimentel Ferreira almost 2 years

    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.