j obe
j obe

Reputation: 2039

Does JSON always need curly braces at the top level?

I've been learning a bit about JSON lately and was trying to understand if it always needs curly braces at the top level or if it can also be an array? Or would the array have to be wrapped in curly braces with a key name and then the array as a value?

For instance, does it have to be this:

{"title":"title 1"}

or could it be this as well:

[1,2,3]

I'm asking in the context of what the spec allows and consumers of the json file might expect, as typically from examples I've seen it, it's always curly braces with key-value pairs inside

Upvotes: 3

Views: 4263

Answers (3)

Quentin
Quentin

Reputation: 943615

The original specification said:

A JSON text is a serialized object or array.

… meaning that the top level needed to be either {} or [].

Many implementations ignored that restriction and allowed any JSON data type (object, array, number, string, boolean, null) to be used at the top level.

The updated specification says:

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.

So now any JSON data type is allowed at the top level, but you need to be aware that some older software might not support anything except objects and arrays at the top level.

Upvotes: 5

Jasneet Dua
Jasneet Dua

Reputation: 4262

it can be of the following:

  1. null
  2. boolean
  3. number
  4. array
  5. object
  6. String: only if its enclosed in quotes

Examples:

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

Upvotes: 1

Sudhanshu Kumar
Sudhanshu Kumar

Reputation: 2044

It can be array, need not to be in curly braces

console.log(JSON.stringify([1,2,3]));

Here's more

Upvotes: 1

Related Questions