81

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: "[]"
ActionOwl
  • 1,473
  • 2
  • 15
  • 20

5 Answers5

147

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'].

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    Incorrect; arrays are also objects. `Json.stringify` ignores non-array properties of arrays. – SLaks Dec 13 '10 at 02:04
  • 9
    @SLaks: I never said that arrays are not objects ;) I'm just saying that one cannot use an array as associative array (ok probably one could *because* they *are* objects, but I think this gets really ugly and confusing and in the end you are responsible for the collapse of the universe...). – Felix Kling Dec 13 '10 at 02:07
  • 13
    Just to clarify the answer: when you initalize it use `{}` or `new Object()`, **NOT** `[]` or `new Array()` – Thymine Aug 28 '12 at 21:41
  • 1
    @Thymine's comment is MOST valuable! PAY ATTENTION on HOW you initialize data in javascript. Use **{}** (!!!) – Eugene Kapustin Jul 23 '19 at 11:57
8

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.

AndreKR
  • 32,613
  • 18
  • 106
  • 168
5

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);
2

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();
Community
  • 1
  • 1
JVE999
  • 3,327
  • 10
  • 54
  • 89
-1

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);
Radu
  • 8,561
  • 8
  • 55
  • 91
Yene Mulatu
  • 2,226
  • 1
  • 17
  • 13