从JSON中提取每个值

时间:2014-01-16 02:46:15

标签: jquery json

我需要解析JSON数据并将每个键的每个值都变成一个变量,这样我就可以在循环之外使用它了,我在这里试图表明我在说什么:

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

谢谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

尝试

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

演示:Fiddle