为什么JSON只允许字符串成为键? [英] Why JSON allows only string to be a key?

查看:367
本文介绍了为什么JSON只允许字符串成为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JSON只允许字符串成为一对的密钥?为什么不是其他类型,如 null 数字 bool 对象数组?考虑到JSON与JavaScript密切相关,我可以从JavaScript规范(ECMA-262)中得出结论吗?我完全是JavaScript的新手,你能不能帮我指出来。

Why does JSON only allow a string to be a key of a pair? Why not other types such as null, number, bool, object, array? Considering JSON is tightly related with JavaScript, could I conclude the reason from JavaScript specification (ECMA-262)? I'm totally a newbie to JavaScript, could you help me to point it out.

推荐答案

JSON格式是故意基于JavaScript对象文字语法和数组文字语法的子集,JavaScript对象只能将字符串作为键 - 因此JSON键也是字符串。 (好吧,你可以使用数字作为JavaScript对象键,但实际上它们会被转换为字符串。)

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.)

注意JSON的重点是它是一个字符串表示数据,以便在不同环境中的不同机器上运行的不同语言编写的程序之间轻松交换。如果你想使用一个对象作为一个键,那么该对象必须以某种方式表示为一个字符串进行传输,但接收语言需要能够使用对象作为键,这意味着你需要这些语言的有限JSON子集只会是一团糟。

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.


考虑JSON是JavaScript的一部分

"Considering JSON is a part of JavaScript"

不,不是。较新的浏览器提供了创建和解析JSON的方法,但除了JSON是字符串格式且JavaScript可以执行字符串之外,它们不是语言的一部分。 JSON 总是一个字符串表示 - 它必须被解析以创建一个在JavaScript(或其他语言)中使用的对象,一旦发生这种情况,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.

(另请注意,JSON的特定位不一定有任何键:它可能只是一个数组,如'[one,two,three]'。)

(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"]'.)

这篇关于为什么JSON只允许字符串成为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆