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
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
本文标签: javascriptDoes JSON always need curly braces at the top levelStack Overflow
版权声明:本文标题:javascript - Does JSON always need curly braces at the top level? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742403638a2468376.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论