简体   繁体   中英

Why is JSON.parse so picky with quotes?

Basically, I am trying to create an object like this by providing a string to JSON.parse():

a = {x:1} 
// -> Object {x: 1}

Intuitively I tried:

a = JSON.parse('{x:1}')
// -> Uncaught SyntaxError: Unexpected token x

After some fiddling I figured out:

a = JSON.parse('{"x":1}')
// -> Object {x: 1}

But then I accidentally changed the syntax and bonus confusion kicked in:

a = JSON.parse("{'x':1}")
//-> Uncaught SyntaxError: Unexpected token '

So now I am looking for an explanation why

  1. one must to quote the property name
  2. the implementation accepts single quotes, but fails on double quotes

The main reason for confusion seems to be the difference between JSON and JavaScript objects.


JSON (JavaScript Object Notation) is a data format meant to allow data exchange in a simple format. That is the reason why there is one valid syntax only. It makes parsing much easier. You can find more information on the JSON website .

Some notes about JSON:

  • Keys must be quoted with "
  • Values might be strings, numbers, objects, arrays, booleans or "null"
  • String values must be quoted with "

JavaScript objects on the other hand are related to JSON (obviously), but not identical. Valid JSON is also a valid JavaScript object. The other way around, however, is not.

For example:

  • keys and values can be quoted with " or '
  • keys do not always have to be quoted
  • values might be functions or JavaScript objects

As pointed out in the comments, because that's what the JSON spec specifies. The reason AFAIK is that JSON is meant to be a data interchange format (language agnostic). Many languages, even those with hash literals, do not allow unquoted strings as hash table keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM