sean2078 sean2078 - 1 month ago 8
Javascript Question

Why does this JSON.parse() evaluation result in an error?

Why does running:

JSON.parse("{ Facet : 'asdf' }");


result in the error
Uncaught SyntaxError: Unexpected token F in JSON at position 1(…)
?

Answer

The key and value (if a string) pairs should always be enclosed inside double quotes "". Otherwise it is not a valid JSON string.

JSON.parse("{Facet:'asdf'}")  // with escaping

supposed to be

JSON.parse("{\"Facet\":\"asdf\"}")  // without escaping

or

JSON.parse('{"Facet":"asdf"}')

If the value is of type Boolean or Number or null, then it need not be enclosed in double quotes.

No double quotes are needed for values for the following types

JSON.parse('{"Facet": 100}')
JSON.parse('{"Facet": true}')
JSON.parse('{"Facet": null}')