Javascript 带引号的 JSON.parse 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3066886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse string with quotes
提问by mjsilva
I have this:
我有这个:
JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5\" SATA2 7200rpm"}}');
JSONLintsays it's perfectly valid json. But on execution I have a JSON.parseerror.
JSONLint说它是完全有效的 json。但是在执行时我有一个JSON.parse错误。
But, if I change my code to:
但是,如果我将代码更改为:
JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5\" SATA2 7200rpm"}}');
(note the double backslash)
(注意双反斜杠)
It works, but now JSONLint says invalid json.
它有效,但现在 JSONLint 说invalid json。
Can someone help to understand this behavior?
有人可以帮助理解这种行为吗?
回答by Dean Povey
It's a difference between the wire format, and what you have to write in your code to get the wire format. When you declare this in code you need the double-\ in your literal so the string gets a single backslash (otherwise it will interpret \" as an escape sequence for just declaring a " and put that in your string). If you print out the value of the literal you will see a single backslash.
这是有线格式与您必须在代码中编写的内容以获取有线格式之间的区别。当你在代码中声明它时,你需要在你的文字中使用双-\,这样字符串就会得到一个反斜杠(否则它会将 \" 解释为一个转义序列,只声明一个 " 并将其放入你的字符串中)。如果您打印出文字的值,您将看到一个反斜杠。

