Search code examples
javascriptarraysjsonstringify

How to stringify an array in Javascript?


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?


Solution

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