29

I have a javascript associative array like one below

 var my_cars= new Array()
 my_cars["cool"]="Mustang";
 my_cars["family"]="Station Wagon";
 my_cars["big"]="SUV";

I want to convert it using Stringify to json object. I want to know after conversion how the json object will look like.

Also when i have this object How I can convert it back to associative array again.

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
user882196
  • 1,691
  • 9
  • 24
  • 39
  • 2
    Dupe? http://stackoverflow.com/questions/459105/convert-a-multidimensional-javascript-array-to-json – Sukumar Aug 17 '11 at 07:18
  • 4
    These types of array are no-no's in javascript. You should ONLY use an object for non-numeric keys like this. Array indexes should be numbers. Javascript objects can use arbitrary values for keys (like in your example). Arrays happen to "appear" to work because Arrays themselves are objects, but you will not find normal Array methods will work on them. – jfriend00 Aug 17 '11 at 07:19
  • In other words: Javascript doesn't have "associative arrays". It has arrays, which are numerically indexed, and objects. – deceze Aug 17 '11 at 07:20

5 Answers5

65

First of all, by making my_cars an array and stringifying it, you don't get what you expect.

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));

This alerts [].

What you want is to start with {}:

var my_cars= {};
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));

This alerts

{"cool":"Mustang","family":"Station Wagon","big":"SUV"}

To get your object back from the string, use JSON.parse().

var s = JSON.stringify(my_cars);
var c = JSON.parse(s);
alert(c.cool);

This alerts "Mustang".

See http://jsfiddle.net/Y2De9/

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
6

No,But the user want to use array not json.

Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for. The JSON array data type cannot have named keys on an array.

If you want named keys, use an Object, not an Array.

*source

var test = [];           // Object
test[0] = 'test';        //this will be stringified

Now if you want key value pair inside the array

test[1] = {};          // Array
test[1]['b']='item';
var json = JSON.stringify(test);

output

"["test",{"b":"item"}]"

so you can use an index with array,so alternatively

var my_cars= [];
my_cars[0]={};
my_cars[0]["cool"]="Mustang";
my_cars[1]={};
my_cars[1]["family"]="Station Wagon";
my_cars[2]={};
my_cars[2]["big"]="SUV";
console.log(JSON.stringify(my_cars));

Output

"[{"cool":"Mustang"},{"family":"Station Wagon"},{"big":"SUV"}]"
Community
  • 1
  • 1
3

Moving my comment into an answer so I can show you a code example.

These types of array are no-no's in javascript. You should ONLY use an object for non-numeric keys like this. Array indexes should be numbers. Javascript objects can use arbitrary values for keys (like in your example). Arrays happen to "appear" to work because Arrays themselves are objects, but you will not find normal Array methods will work on them. For example, look at this code example.

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars.length);  // alerts 0

You have only added properties to the underlying object, not actually added elements to the Array. You should use an Object for this, not an Array. Javascript does not actually have an Associative Array. It has an Object who's properties can often be used like one would use an Associate Array in other languages. But, it's an Object, not an Array.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Indeed, the array elements will never be assigned. The array will be empty after all. – Shef Aug 17 '11 at 07:23
2

"JavaScript does not support arrays with named indexes"

The most close state to an associative array is an array with entries converted to properties (as in your case), so I provide a solution for this exact case.

The fun thing is that Chrome's console makes it feel like an associative array: ["cool":"Mustang", "family":"Station Wagon", "big":"SUV"] (Check with F12)

NOTE: open browser's console before running the snippet

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";


let toAssociative=(keys, values)=> 
    values.reduce((acc, cv)=>{
       acc[acc.shift()]=cv
       return acc;
    }, keys)    


let fromAssociative = (assArr)=>({...assArr})

let serialized = JSON.stringify(fromAssociative(my_cars))

let o = JSON.parse(serialized)

let restored = toAssociative(Object.keys(o) , Object.values(o))

//NOTE: Look at the browser's console before executing (not SO console)

console.log("orig:",my_cars) 
//[cool: "Mustang", family: "Station Wagon", big: "SUV"]

console.log("serialized:",serialized)
//{"cool":"Mustang","family":"Station Wagon","big":"SUV"}
 
console.log("restored:",restored) //NOTE: look at the browser's console (F12)
//[cool: "Mustang", family: "Station Wagon", big: "SUV"]
Marinos An
  • 9,481
  • 6
  • 63
  • 96
0

If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API. In the function you can now decide what to do with value of key is of a specific type.

TechMaze
  • 477
  • 2
  • 9