循环通过json与多个对象

时间:2011-05-19 13:08:48

标签: javascript jquery json

我有一些json代码,里面有多个对象,如下:

这些是对象内的值:

这是json代码:

[{"pk_records_id":"34","record_artist":"Bouncing Souls","record_title":"How I Spent My Summer Vacation","record_added_date":"2011-05-05 17:36:34","record_category":"punkrock","record_price":"11.00","record_cover_link":"img\/Bouncing Souls-How I Spent My Summer Vacation.jpg","record_amount_sold":null,"record_amount_stock":"400","record_description":"A great follow-up to Hopeless Romantic"},{"pk_records_id":"4","record_artist":"Descendents","record_title":"Everything Sucks","record_added_date":"2011-03-11 00:00:00","record_category":"punkrock","record_price":"12.00","record_cover_link":"img\/descendents_everything_sucks.jpg","record_amount_sold":"3124","record_amount_stock":null,"record_description":null}]

这是我尝试使用的代码,因此我可以检索值(显然):

success: function(obj_records){
    $.each(obj_records, function(index, value) {
        alert(obj_records.index.pk_records_id); 
    });             
} 

但这不起作用。如何检索数据?

编辑:

如果我使用此代码,我会在json代码中为每个字符获取一个数组。

$.each(obj_records, function(index, value) {        
    alert(index + " : " + value);     
});  

4 个答案:

答案 0 :(得分:2)

尝试

for (var i=0; i<json.length; i++) {
   alert("JSON Data: " + json[i].pk_records_id);
  // you need to write each key name here
}

DEMO

答案 1 :(得分:1)

从它的外观来看,你正在错误地访问结果。

尝试:

success: function(obj_records){
    $.each(obj_records, function(index, value) {
        alert(value.pk_records_id); 
    });             
} 

答案 2 :(得分:0)

我不确定(不是在测试它的地方),但我认为你想要:

success: function(obj_records){
    $.each(obj_records, function(index, value) {
        alert(value.pk_records_id); 
    });             
} 

答案 3 :(得分:0)

我相信你想要的是:

success: function(obj_records){
    $.each(obj_records, function(index, value) {        
        alert(value.pk_records_id);     
    });             
} 

函数头中的value参数是您要循环的obj_records数组的单个对象。