Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Use {} object notation for string keys –  soktinpk Jun 14 '14 at 20:30

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.