Skip to content Skip to sidebar Skip to footer

JSON.stringify / Parse Oddness With Quote Marks

I am running into an odd little problem with parsing some JSON which has quotes in it. I am using the native JSON.stringify and JSON.parse functions to do this. If I stringify an

Solution 1:

This is a problem which arises from re-evaluating a String without first converting it back into a string literal, so the meaning changes if it is even still valid.
You need to consider what does '\"' as a literal actually mean? The answer is ", without the \. Why?

  • \" resolves to "

If you want to have \" as the result of the literal, you need to write '\\\"'

  • \\ resolves to \
  • \" resolves to "

So basically, the extra slashes are required to escape any characters with special meaning in string literals.

If you did var reOb = JSON.parse($('.stringified').html()); it would work fine as is.


Consider further

str = '\\\"\\\'';      //      \"\'
str = '\"\'';          //      "'
str = '"'';            // SyntaxError: Unexpected token ILLEGAL

As far as I'm aware, JavaScript offers no native implementation to convert strings as desired, so the easiest method I know of is using a replace

function toLiteral(str) {
    var dict = {'\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r'};
    return str.replace(/([\\'"\b\t\n\v\f\r])/g, function ($0, $1) {
        return '\\' + (dict[$1] || $1);
    });
}
toLiteral('foo\\bar'); // "foo\\bar"

Solution 2:

If you generate JS with PHP code you should escape the quotes in your JSON string:

//PHP code generating js code
echo "var myJSONString = \"". str_replace("\"","\\\"",$mySqlJSON)."\";";

Post a Comment for "JSON.stringify / Parse Oddness With Quote Marks"