2014-01-16 92 views
0

我需要解析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); 

謝謝!

+0

你爲什麼不使用JSON VAR你alredy創建你可以只輸入JSON做[0]。 name1從第一個元素獲取teste1。 – sousatg

回答

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

+0

downvoter我錯過了什麼 –