JavaScript 关联数组到 JSON
如何将 JavaScript 关联数组转换为 JSON?
我已经尝试过以下方法:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
How can I convert a JavaScript associative array into JSON?
I have tried the following:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
数组应该只包含带有数字键的条目(数组也是对象,但你真的不应该混合使用它们)。
如果将数组转换为 JSON,该过程将仅考虑数字属性。其他属性将被忽略,这就是为什么您得到一个空数组的原因。如果你看一下数组的长度,可能会更明显:
通常所说的“关联数组”实际上只是 JS 中的一个对象:
可以通过数组表示法或点来访问对象的属性表示法(如果键不是保留关键字)。因此,
AssocArray.a
与AssocArray['a']
相同。Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the
length
of the array:What is often referred to as "associative array" is actually just an object in JS:
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus
AssocArray.a
is the same asAssocArray['a']
.JavaScript 中没有关联数组。但是,有些对象具有命名属性,因此不要使用 new Array 初始化“数组”,然后它就会成为通用对象。
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with
new Array
, then it becomes a generic object.同意将对象保留为对象并将数组保留为数组可能是最佳实践。但是,如果您有一个具有命名属性的对象,并将其视为数组,则可以执行以下操作:
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
我在此处发布了此问题的修复程序,
您可以使用此函数修改
JSON.stringify
进行编码arrays
,只需将其发布到脚本的开头附近(查看上面的链接以获取更多详细信息):I posted a fix for this here
You can use this function to modify
JSON.stringify
to encodearrays
, just post it near the beginning of your script (check the link above for more detail):您可能想将对象推入数组中
You might want to push the object into the array