Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 947
Haoyu Chen Avatar asked Jul 06 '14 04:07

Haoyu Chen


2 Answers

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.

like image 77
adeneo Avatar answered Oct 21 '22 08:10

adeneo


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.

like image 1
Musa Avatar answered Oct 21 '22 08:10

Musa