为什么jQuery.parseJSON不接受换行?

时间:2022-01-04 03:46:48

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.

好的,所以我一直在处理PHP 5.3服务器返回一个手工制作的JSON(因为在5.3中json_encode函数中没有JSON_UNESCAPE_UNICODE)并且在阅读了这个线程并进行了一些测试后,我想我在jQuery中发现了一个问题parseJSON函数。

Suppose I have the following JSON:

假设我有以下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:

如果你使用jsonlint.com检查它,你可以看到它是有效的JSON。但是,如果您尝试以下操作,您会收到一条错误消息:

$(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?

我在jQuery上打开了一个错误报告,因为我认为这是一个错误的错误。你怎么看?

1 个解决方案

#1


12  

It's not a bug, it has to do with how the string literal is handled in JavaScript. When you have:

这不是一个错误,它与如何在JavaScript中处理字符串文字有关。当你有:

'{ "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.

...在传递给parseJSON()之前。这显然不是有效的JSON,因为\ n已被转换为“嗨小男孩”中间的文字换行符?串。

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:

您希望'\ n'序列在转换为文字换行符之前将其转换为parseJSON()函数。要实现这一点,需要在文字字符串中对其进行两次转义。喜欢:

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

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

#1


12  

It's not a bug, it has to do with how the string literal is handled in JavaScript. When you have:

这不是一个错误,它与如何在JavaScript中处理字符串文字有关。当你有:

'{ "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.

...在传递给parseJSON()之前。这显然不是有效的JSON,因为\ n已被转换为“嗨小男孩”中间的文字换行符?串。

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:

您希望'\ n'序列在转换为文字换行符之前将其转换为parseJSON()函数。要实现这一点,需要在文字字符串中对其进行两次转义。喜欢:

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

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