paperboy
paperboy

Reputation: 201

Why does this JSON string fail to parse?

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\"tow"}');

Working example: http://jsfiddle.net/w6yjpame/2/

Upvotes: 0

Views: 307

Answers (1)

jmar777
jmar777

Reputation: 39649

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

Upvotes: 8

Related Questions