Created
March 28, 2012 08:30
-
-
Save johanhdm/2224747 to your computer and use it in GitHub Desktop.
JSON stringify associative array returns empty array - use {} instead of new Array()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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}} |
"{}" 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
which breaks any usage with PHP and other back end scripts - so wrong.