Why does JSON only allow string use?

Why does JSON only allow string be the key of a pair? Why not other types such as null , number , bool , object , array ? Given that JSON is closely related to JavaScript, can I fix the reason from the JavaScript specification (ECMA-262)? I am completely new to JavaScript, could you please help me point this out.

+7
source share
3 answers

The JSON format is intentionally based on a subset of the syntax of a literal JavaScript object and the syntax of an array literal, and JavaScript objects can only contain strings as keys, so JSON keys are also strings. (OK, you can sort usage numbers as keys for JavaScript objects, but in fact they are converted to strings.)

Note that the JSON point is that it is a string representation of the data that makes it easy to exchange between programs written in different languages, running on different computers in different environments. If you want to use the object as a key, then this object must be somehow presented as a string for transmission, but then the host language will have to use the objects as keys, and this will mean that you will need a limited subset of JSON for those languages that would be just a mess.

"Given that JSON is part of JavaScript"

No, it is not. Newer browsers provide methods for creating and parsing JSON, but they are not part of the language as such, except that JSON is a string format and JavaScript can execute strings. JSON is always a string representation - it must be parsed to create an object for use in JavaScript (or other languages), and as soon as this happens, JavaScript (or other languages) process the resulting object in the same way as any other object.

(Note also that a particular JSON bit does not necessarily have any keys at all: it can just be an array, for example '["one","two","three"]' .)

+6
source

Because the specification is written that way.

+1
source

The main reason, according to the opening of the JSON view, "when parsing JSON data, is there a chance / possibility that the key that you use for the value link may be a reserved word in your syntax language"

Refer to talk from Douglas Crockford, who is the pioneer of the JSON representation.

Example: { id: 1234, name: "foo", do: "somthing" }

Since JSON is interoperability in different languages, we can use this dataset in many languages. But the word do is a keyword in Javascript . This will result in a syntax error during parsing.

+1
source

All Articles