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);
}
});
Link to the fiddle.
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:
'{ "hello": "hi\nlittle boy?" }'
...your string will get parsed into:
{ "hello": "hi
little boy?" }
...before it is passed to parseJSON()
. And that clearly is not valid JSON, since the \n
has 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 the parseJSON()
function before being converted to a literal newline. For that to happen, it needs to be escaped twice in the literal string. Like:
'{ "hello": "hi\\nlittle boy?" }'
Example: http://jsfiddle.net/m8t89/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With