admin管理员组

文章数量:1336117

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
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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:

  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

本文标签: javascriptDoes JSON always need curly braces at the top levelStack Overflow