为什么这个json字符串无法解析

pap*_*boy 0 javascript jquery json

也许我现在只是看不到它,但为什么这个json字符串无法解析?(因为它有效)

var content = $.parseJSON('{"foobar" : "hallo\"tow"}');
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/w6yjpame/2/

谢谢你的帮助!

jma*_*777 8

因为您在字符串文字中创建了JSON,所以需要转义它\自己:

var content = $.parseJSON('{"foobar" : "hallo\\"tow"}');

console.log(content);
Run Code Online (Sandbox Code Playgroud)

说明:

在JSON中,"字符使用\字符进行转义.这使得以下完全有效的JSON:

{"foobar" : "hallo\"tow"}
Run Code Online (Sandbox Code Playgroud)

现在,在您的示例中,您在JavaScript字符串中构造此JSON值:

'{"foobar" : "hallo\"tow"}'
Run Code Online (Sandbox Code Playgroud)

这引入了一个微妙的问题,因为JavaScript字符串也会转义"\字符的字符.也就是说,以下字符串文字:

'\"'
Run Code Online (Sandbox Code Playgroud)

...持有价值:

"
Run Code Online (Sandbox Code Playgroud)

现在,再次将它应用于您的示例,我们发现此字符串文字:

'{"foobar" : "hallo\"tow"}'
Run Code Online (Sandbox Code Playgroud)

......实际上保持着价值:

{"foobar" : "hallo"tow"}
Run Code Online (Sandbox Code Playgroud)

如你所见,我们失去了我们的\.幸运的是,这很容易解决,因为\字符也可以使用\JavaScript字符串中的字符进行转义,这正是我的解决方案所做的.所以现在,修改后的字符串文字:

'{"foobar" : "hallo\\"tow"}'
Run Code Online (Sandbox Code Playgroud)

被解析为包含预期值的字符串:

{"foobar" : "hallo\"tow"}
Run Code Online (Sandbox Code Playgroud)

...然后可以将其解析为格式正确的JSON.

在从textareaajax请求读取或作为ajax请求的结果时没有此问题的原因是JSON值未由字符串文字定义.额外\的只是由于字符串文字语法而需要,并且竞争"对手是谁首先要逃避引用(好吧,不是真正的竞争......字符串文字总是胜利).