Why doesn't jQuery.parseJSON accept newlines?

Ok, so I was dealing with a PHP 5.3 server returning manual JSON (because in 5.3 there is no JSON_UNESCAPE_UNICODE in the json_encode function) and after reading this thread and doing some tests, I think I found a problem in the jQuery parseJSON function.

Suppose I have the following JSON:

 { "hello": "hi\nlittle boy?" } 

If you test it using jsonlint.com , you can see it with valid JSON. However, if you try the following, you will receive an error message:

 $(function(){ try{ $.parseJSON('{ "hello": "hi\nlittle boy?" }'); } catch (exception) { alert(exception.message); } });​ 

Link to the script .

I opened the error report in jQuery because I think this is the correct error. What do you think?

+4
source share
1 answer

This is not an error, it is due to the way the string literal is processed in JavaScript. When you have:

 '{ "hello": "hi\nlittle boy?" }' 

... your string will be parsed for:

 { "hello": "hi little boy?" } 

... before it is passed to parseJSON() . And this is clearly not JSON, since \n was converted to a newline letter in the middle of "hello little boy"? line.

You want the sequence " \n " to jump to the parseJSON() function before converting to a literal newline. For this to happen, it must be double-escaped in a literal string. How:

 '{ "hello": "hi\\nlittle boy?" }' 

Example: http://jsfiddle.net/m8t89/2/

+12
source

Source: https://habr.com/ru/post/1438209/


All Articles