Reputation: 2039
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
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
Reputation: 4262
it can be of the following:
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
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