Andre
Andre

Reputation: 849

Extract each value from JSON

I need to parse JSON data and get each value from each key into a variable so I can use it outside of the loop, I am trying here to show what I am talking about:

var j ='[{"name1":"test1","name2":"test2","name3":"test3","name4":"test4"}]';

var json = $.parseJSON(j);

var items = [];

$(json).each(function(key,val){

$.each(val,function(k,v){

   alert(k+" : "+ v); 
   // push here ??

 });

});

var name1 = items[name1];
alert(name1);

Thank you!

Upvotes: 0

Views: 90

Answers (2)

Rami Enbashi
Rami Enbashi

Reputation: 3556

http://jsfiddle.net/xR863/

var j ='[{"name1":"test1","name2":"test2","name3":"test3","name4":"test4"}]';

var json = $.parseJSON(j);


var items = [];

$(json).each(function(key,val){

$.each(val,function(k,v){

  // alert(k+" : "+ v); 
   // push here ??
    items[k] = v;

 });

});


var name1 = items['name1'];
alert(name1);

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

Try

var j = '[{"name1":"test1","name2":"test2","name3":"test3","name4":"test4"}]';

var json = $.parseJSON(j);
//since there is only one item in the array, it won't work if there are muliple items in the array
//in this case your can just use the first object in the array as it contains the key value pair
var items = json[0];

//use the key name1 - use bracket notation of dot notation to access the member
var name1 = items['name1'];//or items.name1
alert(name1);

Demo: Fiddle

Upvotes: 0

Related Questions