最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.parse allows null as value - Stack Overflow

programmeradmin5浏览0评论

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 that JSON.stringify has gone over resulting in strings. I simply throw null into my JSON.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
Add a ment  | 

2 Answers 2

Reset to default 9

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.

See the specification:

  1. 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".

发布评论

评论列表(0)

  1. 暂无评论