Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery.parseJSON does not accept newlines?

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?

like image 792
José Tomás Tocino Avatar asked Dec 16 '22 18:12

José Tomás Tocino


1 Answers

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/

like image 170
aroth Avatar answered Dec 18 '22 09:12

aroth