Why does this JSON string fail to parse?

后端 未结 1 1377
情话喂你
情话喂你 2021-01-26 03:39

Maybe I just don\'t see it at the moment, but why does this JSON string fail to parse? It should be valid.

var content = $.parseJSON(\'{\"foobar\" : \"hallo\\\"t         


        
相关标签:
1条回答
  • 2021-01-26 04:11

    Because you're creating that JSON in a string literal, you need to escape the \ itself:

    var content = $.parseJSON('{"foobar" : "hallo\\"tow"}');
    
    console.log(content);
    

    Explanation:

    In JSON, " characters are escaped using \ characters. That makes the following perfectly valid JSON:

    {"foobar" : "hallo\"tow"}
    

    Now, in your example, you were constructing this JSON value within a JavaScript string:

    '{"foobar" : "hallo\"tow"}'
    

    This introduces a subtle issue, due to the fact that JavaScript strings also escape " characters with \ characters. That is, the following string literal:

    '\"'
    

    ... holds the value:

    "
    

    Now, applying that to your example again, we find that this string literal:

    '{"foobar" : "hallo\"tow"}'
    

    ... actually holds the value:

    {"foobar" : "hallo"tow"}
    

    As you can see, we've lost our \. Fortunately, this is easy to work around, as \ characters can also be escaped with \ characters in JavaScript strings, which is what my solution does. So now, the revised string literal:

    '{"foobar" : "hallo\\"tow"}'
    

    gets parsed as a string holding the intended value:

    {"foobar" : "hallo\"tow"}
    

    ... which can then be parsed as properly formatted JSON.

    The reason you don't have this issue when reading from a textarea or as the result of an ajax request is that the JSON value isn't being defined by a string literal. The extra \ is only required due to string literal syntax, and the competition going on for who's going to escape the " quote first (well, not really a competition... the string literal always wins).

    0 讨论(0)
提交回复
热议问题