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']
.
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array
, then it becomes a generic object.
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
tempArr.push(objectArr[element]);
});
let json = JSON.stringify(tempArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With