Haoyu Chen
Haoyu Chen

Reputation: 1810

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?

Upvotes: 6

Views: 6898

Answers (2)

Musa
Musa

Reputation: 97672

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.

Upvotes: 1

adeneo
adeneo

Reputation: 318222

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.

Upvotes: 16

Related Questions