How can I convert a JavaScript associative array into JSON?
I have tried the following:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length
of the array:
> AssocArray.length
0
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a
is the same as AssocArray['a']
.