loop through json with multiple objects

10,646

Solution 1

try with

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

Solution 2

From the looks of it, you're accessing the result incorrectly.

Try:

success: function(obj_records){
    $.each(obj_records, function(index, value) {
        alert(value.pk_records_id); 
    });             
} 
Share:
10,646
Veltar
Author by

Veltar

Forever in limbo.

Updated on June 13, 2022

Comments

  • Veltar
    Veltar almost 2 years

    I have some json-code with has multiple objects in it, as such:

    These are the values inside the object:

    This is the json-code:

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

    And this is the code I try to use, so I would be able to retrieve the values (obviously):

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

    But this doesn't work. How can I retrieve the data?

    Edit:

    If I use this code, I get an array for every single character in my json-code.

    $.each(obj_records, function(index, value) {        
        alert(index + " : " + value);     
    });  
    
  • Veltar
    Veltar almost 13 years
    I get an infinite number of popups, all saying undefined.
  • Alexander Kahoun
    Alexander Kahoun almost 13 years
    Veltar, since your example provided an alert inside a loop, I am only editing based on your example. Having an alert inside a loop will create a lot of messages, the same as the number in your array.
  • Alexander Kahoun
    Alexander Kahoun almost 13 years
    Rory, I'm sorry but your method is incorrect. The obj_records is the array, not the individual object in the array. Please reference the jquery api: api.jquery.com/jQuery.each
  • Rory McCrossan
    Rory McCrossan almost 13 years
    Now the OP has edited to include his JSON you are correct. I will remove my comment.
  • Veltar
    Veltar almost 13 years
    Very strange, it works in your demo, when I implement it I have an infinite amount of alerts that say "Undefined".