Sherlock Sherlock - 1 month ago 7
JSON Question

JSON.stringify doesn't work with normal Javascript array

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?

Answer

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);
Comments