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 must be missing something here, but the following code (Fiddle) returns an empty string:

var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);

What is the correct way of JSON'ing this array?

share|improve this question
3  
That's not an array, you are just setting two properties –  Toni Toni Chopper Apr 24 '13 at 15:43
1  
possible duplicate of JavaScript associative array to JSON –  Felix Kling Apr 24 '13 at 15:43
3  
Start out with var test = {}; instead –  Ian Apr 24 '13 at 15:43

4 Answers 4

up vote 31 down vote accepted

Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for. The JSON array data type cannot have named keys on an array.

If you want named keys, use an Object, not an Array.

var test = {};           // Object
test['a'] = 'test';
test['b'] = [];          // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);
share|improve this answer

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

share|improve this answer
    
This is just wrong. JSON.stringify([15,12]) will work. It will give "[15,12]" –  devnull69 May 19 at 12:24

Nice explanation and example above. I found this (JSON.stringify() bizarreness) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}

it works fine and the output of the test:

console.log(json);

"{"a":"test","b":["item","item2","item3"]}"

share|improve this answer
    
I had some issues with a site that overwrite Date, so when I use the Date.toJSON fails I so I added: Date.prototype.toJSON = Date.prototype.toISOString; –  Adrien Louis Combecau Sep 16 '14 at 13:05

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();
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.