Is there any difference in JSON Key when using single quote and double quote?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 08:36:45

问题


I ran two pieces of javascript codes in a online JS running platform:Website Link

pets = '{'pet_names':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);

Code with double quotes ("pet_names") would be OK but with single quotes('pet_names') would remind a error:"Unexpected identifier"

pets = '{"pet_names":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);

So, why do it would happen?


回答1:


In JSON only double quotes are valid.

You can find the standard on JSON.org

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.

In other words, no strings in single quotes.




回答2:


The first one didn't work because you have a syntax error where you try to define your string literal
you probably wanted

pets = '{\'pet_names\':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';

notice the quotes are escaped.

Now if you used that string in the json parser you would still get an error(SyntaxError: Unexpected token ') because keys in JSON must be defined with double quotes, using single quotes is valid for defining JavaScript object literals which is separate from JSON.



来源:https://stackoverflow.com/questions/24592841/is-there-any-difference-in-json-key-when-using-single-quote-and-double-quote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!