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
lengthof the array:What is often referred to as “associative array” is actually just an object in JS:
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus
AssocArray.ais the same asAssocArray['a'].