Ok so I’ve been dealing with a PHP 5.3 server returning a hand-made JSON (because in 5.3 there’s no JSON_UNESCAPE_UNICODE in the json_encode function) and after reading this thread and making some tests, I think I’ve found a problem in jQuery’s parseJSON function.
Suppose I have the following JSON:
{
"hello": "hi\nlittle boy?"
}
If you check it using jsonlint.com you can see it’s valid JSON. However, if you try the following, you get an error message:
$(function(){
try{
$.parseJSON('{ "hello": "hi\nlittle boy?" }');
} catch (exception) {
alert(exception.message);
}
});
I’ve opened a bug report at jQuery, because I think it’s a proper bug. What do you think?
It’s not a bug, it has to do with how the string literal is handled in JavaScript. When you have:
…your string will get parsed into:
…before it is passed to
parseJSON(). And that clearly is not valid JSON, since the\nhas been converted to a literal newline character in the middle of the “hi little boy?” string.You want the ‘
\n‘ sequence to make it to theparseJSON()function before being converted to a literal newline. For that to happen, it needs to be escaped twice in the literal string. Like:Example: http://jsfiddle.net/m8t89/2/