简体   繁体   中英

How do I loop through a JSON list?

I have multiple items in my JSON list. I want to loop through it and display it on my page. I can't seem to get to the next object though.

{
"room":[
    {"campusName":"A",
     "buildingCode":"B",
     "roomNumber":"208",
     "times":["7-8", "9-10"]
}],

"room2":[
{"campusName":"C",
  "buildingCode":"D",
  "roomNumber":"208",
  "times":["7-8", "9-10"
 ]}
]}
$(document).ready(function(){
  $.getJSON("data.json", function(data){
    $.each(data.room, function(){
        for(var i = 0; i < data.length; i++){
            $("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>");
        }
    });
  });
});

Try this

var list = '';

$.each(data, function (i, root) {
  $.each(root, function (i, el) {
    list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>";
  });  
});

$('ul').html(list);

Example

If root's has only one element in array

var list = '';

$.each(data, function (i, root) {
  list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>";
});

$('ul').html(list); 

Example

$.each(data, ..) --> Each element will be:

"room":[
    {"campusName":"A",
     "buildingCode":"B",
     "roomNumber":"208",
     "times":["7-8", "9-10"]
}]

Then, this[0] will provide the object you need to construct your li :

$.each(data, function(){
            $("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>");
    });

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM