最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Why jQuery.parseJSON does not accept newlines? - Stack Overflow

programmeradmin2浏览0评论

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

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. 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?

Share Improve this question edited May 23, 2017 at 12:12 CommunityBot 11 silver badge asked Oct 7, 2012 at 2:05 José Tomás TocinoJosé Tomás Tocino 10.1k5 gold badges47 silver badges82 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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/m8t89/2/

发布评论

评论列表(0)

  1. 暂无评论