为什么此JSON字符串无法解析? [英] Why does this JSON string fail to parse?

查看:221
本文介绍了为什么此JSON字符串无法解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我暂时看不到它,但是为什么这个JSON字符串无法解析?应该是有效的.

Maybe I just don't see it at the moment, but why does this JSON string fail to parse? It should be valid.

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

工作示例: http://jsfiddle.net/w6yjpame/2/

推荐答案

由于要以字符串文字形式创建JSON,因此需要转义\本身:

Because you're creating that JSON in a string literal, you need to escape the \ itself:

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

console.log(content);


说明:


Explanation:

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

In JSON, " characters are escaped using \ characters. That makes the following perfectly valid JSON:

{"foobar" : "hallo\"tow"}

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

Now, in your example, you were constructing this JSON value within a JavaScript string:

'{"foobar" : "hallo\"tow"}'

由于JavaScript字符串转义"字符和\字符,因此引入了一个微妙的问题.即,以下字符串文字:

This introduces a subtle issue, due to the fact that JavaScript strings also escape " characters with \ characters. That is, the following string literal:

'\"'

...保留值:

"

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

Now, applying that to your example again, we find that this string literal:

'{"foobar" : "hallo\"tow"}'

...实际上拥有值:

... actually holds the value:

{"foobar" : "hallo"tow"}

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

As you can see, we've lost our \. Fortunately, this is easy to work around, as \ characters can also be escaped with \ characters in JavaScript strings, which is what my solution does. So now, the revised string literal:

'{"foobar" : "hallo\\"tow"}'

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

gets parsed as a string holding the intended value:

{"foobar" : "hallo\"tow"}

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

... which can then be parsed as properly formatted JSON.

textarea读取时或由于ajax请求而没有此问题的原因是JSON值不是由字符串文字定义的.仅由于字符串文字语法而需要额外的\,并且争夺谁先抢占"引号的竞争正在进行(嗯,这并不是真正的竞争……字符串文字总是会获胜).

The reason you don't have this issue when reading from a textarea or as the result of an ajax request is that the JSON value isn't being defined by a string literal. The extra \ is only required due to string literal syntax, and the competition going on for who's going to escape the " quote first (well, not really a competition... the string literal always wins).

这篇关于为什么此JSON字符串无法解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆