Why JSON allows only string to be a key?

你。 提交于 2019-11-29 03:55:09

The JSON format is deliberately based on a subset of JavaScript object literal syntax and array literal syntax, and JavaScript objects can only have strings as keys - thus JSON keys are strings too. (OK, you can sort of use numbers as JavaScript object keys, but really they get converted to strings.)

Note that the point of JSON is that it is a string representation of data to allow easy exchange between programs written in different languages running on different machines in different environments. If you wanted to use an object as a key then that object would in turn have to be somehow represented as a string for transmission, but then the receiving language would need to be able to use objects as keys and that would mean you'd need a limited subset of JSON for those languages which would just be a mess.

"Considering JSON is a part of JavaScript"

No, it isn't. Newer browsers provide methods for creating and parsing JSON, but they're not part of the language as such except that JSON is a string format and JavaScript can do strings. JSON is always a string representation - it has to be parsed to create an object for use within JavaScript (or other languages) and once that happens JavaScript (or the other languages) treat the resulting object the same as any other object.

(Note also that a particular bit of JSON doesn't necessarily have any keys at all: it could just be an array, like '["one","two","three"]'.)

Main reason according to the discoverer of JSON representation is, "while parsing json data, there is a chance/possibility that, key you are using to refer a value might be a reserved word in your parsing language"

Refer this talk by Douglas Crockford, who is the discoverer of JSON representation.

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

Since JSON is a cross language compatibility we can use this data set in many language. But, the word do is a keyword in Javascript. It will end up in syntax error while parsing.

Because that is the way the specification was written.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!