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?

Upvotes: 1

Views: 3126

Answers (2)

Oriol
Oriol

Reputation: 288080

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.

Upvotes: 2

Guffa
Guffa

Reputation: 700262

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.

Upvotes: 2

Related Questions