Javascript jQuery.parseJSON 单引号与双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14355655/
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
jQuery.parseJSON single quote vs double quote
提问by sadaf2605
What actually the difference between this?
这实际上有什么区别?
This works fine:
这工作正常:
var obj1 = jQuery.parseJSON('{"orderedList": "true"}');
document.write("obj1 "+ obj1.orderedList );
but the following does not work:
但以下不起作用:
var obj2 = jQuery.parseJSON("{'orderedList': 'true'}");
document.write("obj2 "+ obj2.orderedList );
Why is that?
这是为什么?
回答by ch4nd4n
That's because double quotes is considered standard while single quote is not. This is not really specific to JQuery, but its about JSON standard. So irrespective of JS toolkit, you should expect same behaviour.
那是因为双引号被认为是标准的,而单引号不是。这并不是真正特定于 JQuery,而是关于JSON 标准。因此,无论 JS 工具包如何,您都应该期待相同的行为。
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
值可以是双引号中的字符串、数字、真假或空值、对象或数组。这些结构可以嵌套。
Update
更新
Or perhaps its a duplicate of jQuery single quote in JSON response
或者它可能是JSON 响应中jQuery 单引号的副本
回答by David M
As per the API documentation, double quotes are considered valid JSON, single quotes aren't.
根据 API 文档,双引号被认为是有效的 JSON,单引号不是。
回答by Parveen Verma
Go to www.Jsonlint.comwebsite and check your single quotes json string you will found that it is not a valid json string. Because double quotes json is standard json format.
转到www.Jsonlint.com网站并检查您的单引号 json 字符串,您会发现它不是有效的 json 字符串。因为双引号 json 是标准的 json 格式。
jsonlint.com is a website to check json format right or not.
jsonlint.com 是一个检查 json 格式正确与否的网站。
回答by Macfer Ann
You could use replace to fix this. This worked for me.
您可以使用替换来解决此问题。这对我有用。
var str = "{'orderedList': 'true'}";
str = str.replace(/\'/g, '\"');
JSON.parse(str);

