Search code examples
javascriptjson

Shouldn't JSON.parse(null) and JSON.parse(false) throw exceptions?


Argument to JSON.parse(...) is supposedly a valid json string, but null and false are not strings.

Note, I am passing javascript null not 'null' (as a string). Obviously JSON.parse('null') should work just fine.

JSON.parse(null) returns null?!
JSON.parse(false) returns null?!

Shouldn't they they throw exceptions?

JSON.parse(undefined) throws exception, as expected
JSON.parse('') throws exception, as expected

(Tested in recent Chrome and Firefox)


Solution

  • JSON.parse explicitly casts the argument to a string. null results in the string 'null' and false in the string 'false'. null and false are valid JSON values, so they decode just fine.