问题描述
如何将JavaScript关联数组转换为JSON?
How can I convert a JavaScript associative array into JSON?
我尝试过以下操作:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
推荐答案
数组应该只有数字键的条目(数组也是对象,但你真的不应该混合它们)。
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
如果将数组转换为JSON,则该过程仅考虑数值属性。其他属性被简单地忽略,这就是为什么你得到一个空数组的结果。如果你看一下数组的长度
,这可能更明显:
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:
> AssocArray.length
0
通常所谓的关联数组实际上只是JS中的一个对象:
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
可以访问对象的属性通过数组表示法或点表示法(如果键不是保留关键字)。因此 AssocArray.a
与 AssocArray ['a']
相同。
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 as AssocArray['a']
.
这篇关于JavaScript关联数组到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!