Tiberiu Tiberiu - 6 months ago 64
JSON Question

can a JSON start with [?

From what I can read on json.org, all JSON strings should start with

{
(curly brace), and
[
characters (square brackets) represent an array element in JSON.

I use the
json4j
library, and I got an input that starts with
[
, so I didn't think this was valid JSON. I looked briefly at the JSON schema, but I couldn't really find it stated that a JSON file cannot start with
[
, or that it can only start with
{
.

Answer

JSON can be either an array or an object. Specifically off of json.org:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an
    array, vector, list, or sequence.

It then goes on to describe the two structures as: A JSON object A JSON array

Note that the starting and ending characters are curly brackets and square brackets respectively.

Edit
And from here: http://www.ietf.org/rfc/rfc4627.txt

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.

Update (2014)

As of March 2014, there is a new JSON RFC (7159) that modifies the definition slightly (see pages 4/5).

The definition per RFC 4627 was: JSON-text = object / array

This has been changed in RFC 7159 to: JSON-text = ws value ws

Where ws represents whitespace and value is defined as follows:

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

false null true

So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values false, null or true.

Also, this has changed from my previous RFC 4627 quote (emphasis added):

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 value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.