Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse allows null as value

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 come 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?

like image 562
Stephan-v Avatar asked Sep 28 '17 08:09

Stephan-v


People also ask

Can JSON parse null value?

New! Save questions or answers and organize your favorite content. Learn more.

Does JSON allow empty string?

In Spark 2.4 and below, the JSON parser allows empty strings. Only certain data types, such as IntegerType are treated as null when empty. In Spark 3.0 and above, the JSON parser does not allow empty strings.

Does JSON allow undefined values?

Placing a defined value into a variable makes it not undefined. The only option is that an undefined value was stored into that property or that that JSON was not generated automatically.

Can null be a JSON key?

JSON object keys must be strings according to the specification. Therefore null is not allowed as JSON object key. So the reason it fails is because what you are returning can not be serialized to a valid JSON structure.


1 Answers

The ECMAScript spec says as the first step for JSON.parse:

  1. Let JText be ToString(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.

like image 171
deceze Avatar answered Oct 20 '22 13:10

deceze