问题
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