Skip to content

Instantly share code, notes, and snippets.

@johanhdm
Created March 28, 2012 08:30
Show Gist options
  • Save johanhdm/2224747 to your computer and use it in GitHub Desktop.
Save johanhdm/2224747 to your computer and use it in GitHub Desktop.
JSON stringify associative array returns empty array - use {} instead of new Array()
//JSON.stringify an associative array using the Array object --> does not work
var array1 = new Array();
array1['a'] = { x : 1, y : 2 };
console.log(array1);
//outputs : [ a: { x: 1, y: 2 } ]
console.log(JSON.stringify(array1));
//outputs : []
//JSON.stringify associative array using {} --> works!
var array2 = {};
array2['b'] = { x : 1, y : 2 };
console.log(array2);
//outputs : { b: { x: 1, y: 2 } }
console.log(JSON.stringify(array2));
//outputs : {"b":{"x":1,"y":2}}
@audas
Copy link

audas commented Oct 14, 2014

which breaks any usage with PHP and other back end scripts - so wrong.

@FrischePeterSilie
Copy link

"{}" creates and object, not an array. In JS there are no associative arrays, you can only use objects for that matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment