Sherlock Sherlock - 1 year ago 85
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);

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

Answer Source

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
var json = JSON.stringify(test);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download