Wednesday, 15 May 2013

javascript - Why does this json string fails to parse -



javascript - Why does this json string fails to parse -

maybe don't see @ moment why json string fails parse? (since valid)

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

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

thanks help!

because you're creating json in string literal, need escape \ itself:

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

explanation:

in json, " characters escaped using \ characters. makes next valid json:

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

now, in example, constructing json value within javascript string:

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

this introduces subtle issue, due fact javascript strings also escape " characters \ characters. is, next string literal:

'\"'

... holds value:

"

now, applying illustration again, find string literal:

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

... holds value:

{"foobar" : "hallo"tow"}

as can see, we've lost our \. fortunately, easy work around, \ characters can escaped \ characters in javascript strings, solution does. now, revised string literal:

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

gets parsed string holding intended value:

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

... can parsed formatted json.

the reason don't have issue when reading textarea or result of ajax request json value isn't beingness defined string literal. \ required due string literal syntax, , competition going on who's going escape " quote first (well, not competition... string literal wins).

javascript jquery json

No comments:

Post a Comment