How to stringify an array in Javascript?

北城以北 提交于 2019-12-24 13:44:24

问题


I am running the following piece of code:

var arr = [];

arr["aaa"] = {
    "xxx" : 1,
    "ttt" : 2
};

arr["bbb"] = {
    "xxx" : 5,
    "qqq" : 6
};

var tmp = JSON.stringify(arr);

alert(tmp);

But the result is []. How does one stringify an array with string keys and object values?


回答1:


Use

var arr = {};

Arrays should only be used for numerically indexed data, not arbitrary properties. Of course you are able to do it, because they are, in fact, objects. But it won't work in JSON.

Instead, just use objects.




回答2:


You can't do that, for two reasons:

  • The stringify method only consider the data in the array, not properties.
  • There is no JSON format for an array with properties.

If you want the representation of an array in the JSON, you need to put the data in the actual array, not as properties in the array object.

If you want the properties in the JSON, you need to use a plain object instead of an array.



来源:https://stackoverflow.com/questions/24223990/how-to-stringify-an-array-in-javascript

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