如何循环JSON列表?

时间:2015-02-08 09:14:00

标签: javascript json

我的JSON列表中有多个项目。我想循环遍历它并在我的页面上显示它。我似乎无法进入下一个对象。

{
"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>");
        }
    });
  });
});

2 个答案:

答案 0 :(得分:3)

试试这个

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

如果root's在数组中只有一个元素

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

答案 1 :(得分:2)

$.each(data, ..) - &gt;每个元素都是:

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

然后,this[0]将提供构建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