62

Hot debate today:

Is the text stream null valid JSON?

According to http://www.ietf.org/rfc/rfc4627.txt?number=4627:

...
2. JSON Grammar

A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.

A JSON text is a serialized object or array.

Should this interpreted as both statements must be true in order for the text to be valid JSON?

However, many other libraries seem to permit it, and indeed, it seems like a single valid token could be a legitimate result.

Is there a definitive answer?

Robert Altman
  • 5,355
  • 5
  • 33
  • 51

2 Answers2

85

RFC 7159 and its successor RFC 8259 drop the limitation that a JSON text must be an object or an array. The grammar specifies:

JSON-text = ws value ws

where

value = false / null / true / object / array / number / string

Thus, "null" is now a valid JSON document.

dbc
  • 104,963
  • 20
  • 228
  • 340
niksnut
  • 1,129
  • 1
  • 8
  • 5
30

[Note! This answer is no longer correct, see answer by @niksnut.]

Yes, both statements must be true. The literal token null is a JSON value. A JSON text is a serialized object or array, which requires {} or [].

peak
  • 105,803
  • 17
  • 152
  • 177
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
  • How does it come then that most JSON parsers out there accept `null' as valid document? A typical examples are Node.JS (JSON.parse('null') => null or echo 'null' | python -mjson.tool => null. – wh81752 Feb 09 '12 at 09:42
  • 1
    echo '7' | python -mjson.tool yields 7, so I infer that tool apparently is willing to parse isolated JSON literal values as well as complete (object or array) JSON texts. – Russell Borogove Feb 09 '12 at 18:43
  • Ruby’s JSON parser rejects just `null` as a value by default: `ruby -r json -e 'JSON.parse("null")'` givens “unexpected token at 'null' (JSON::ParserError)” – Andrew Marshall Jul 20 '13 at 02:08
  • Some parsers also choke on `"[]"`. – Erik Kaplun Feb 13 '14 at 20:53
  • 5
    Note! This answer is no longer correct, see @niksnut answer below – Fractalf Jan 08 '18 at 13:52
  • @moderators: (if any listening) Should we as community edit this answer with warning that it's outdated? – Zbigniew Zagórski Apr 09 '18 at 13:28