Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a javascript associative array into json object using stringify and vice versa

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.

like image 830
user882196 Avatar asked Sep 04 '25 17:09

user882196


2 Answers

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/

like image 188
Ray Toal Avatar answered Sep 07 '25 11:09

Ray Toal


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"}]"