I am passing null to JSON.parse() and although the first parameter is documented saying that it should be a string value, it still works to supply null
.
How e this does not throw an error even though even though the documentation state this is for strings and can this be safely and reliable used in multiple browsers?
I am passing null to JSON.parse() and although the first parameter is documented saying that it should be a string value, it still works to supply null
.
How e this does not throw an error even though even though the documentation state this is for strings and can this be safely and reliable used in multiple browsers?
Share Improve this question asked Sep 28, 2017 at 8:29 Stephan-vStephan-v 20.3k32 gold badges121 silver badges210 bronze badges 5- check the below answer stackoverflow./questions/21120999/representing-null-in-json – Suvethan Nantha Commented Sep 28, 2017 at 8:32
-
I feel like that question is different since it talks about using
null
within JSON objects. JSON objects thatJSON.stringify
has gone over resulting in strings. I simply thrownull
into myJSON.parse()
directly. – Stephan-v Commented Sep 28, 2017 at 8:34 -
I assume
parse
might internally cast the given value to a string, which would be"null"
, which is a valid JSON value. – deceze ♦ Commented Sep 28, 2017 at 8:34 -
Ok if that is the case I wonder how reliable this is
cross-browser
. – Stephan-v Commented Sep 28, 2017 at 8:36 - JSON.parse("null") or JSON.parse(null) both of them are casted as "null" which is a valid json, but if you pass JSON.parse('') it will throw an exception it's an empty string – Suvethan Nantha Commented Sep 28, 2017 at 8:42
2 Answers
Reset to default 9The ECMAScript spec says as the first step for JSON.parse
:
- Let
JText
beToString(text)
.
Meaning it'll cast whatever argument it's given to a string, and null
casts to "null"
, which is the valid JSON representation of null
.
Note that a single such JSON primitive shouldn't be valid, a JSON string should be wrapped in an object or array. But parsers have traditionally been lax with that, partially due to it making the implementation simpler I suppose.
See the specification:
- Let JText be ToString(text).
It doesn't require that the first argument be a string, it attempts to convert it to a string.
"" + null
will give you "null"
which is a string containing valid JSON.
This is also in the spec:
Null: Return "null".