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
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
Share edited Dec 24, 2020 at 18:22 j obe asked Dec 24, 2020 at 14:32 j obej obe 2,0494 gold badges19 silver badges34 bronze badges 2- json/json-en.html – PM 77-1 Commented Dec 24, 2020 at 14:35
- Are you asking about a standard or what you practically can get away with? – PM 77-1 Commented Dec 24, 2020 at 14:37
3 Answers
Reset to default 5The 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.
It can be array, need not to be in curly braces
console.log(JSON.stringify([1,2,3]));
Here's more
it can be of the following:
- null
- boolean
- number
- array
- object
- 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