如何使用Javascript检索JSON中的子数组元素?

时间:2015-02-08 07:22:26

标签: javascript json

我有这个JSON对象,我想用javascript解析它。我能够得到B,A和208,但是我很难获得数据。

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

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

2 个答案:

答案 0 :(得分:0)

data.times的元素只是字符串,而不是对象,所以你不应该为它们编制索引。它应该只是:

$.each(data.times, function() {
    $("ul").append("<li>stuff: " + this + "</li>");
});

此外,您的第一个$.each()回调中的参数列表是错误的。它应该是function(i, data) - 第一个参数是数组索引(或者对象属性名称,如果你在对象上进行迭代),第二个参数是值。

&#13;
&#13;
var data = {
  "room": [{
    "campusName": "B",
    "buildingCode": "A",
    "roomNumber": "208",
    "times": [
      "7-8", "9-10"
    ]
  }]
};

$.each(data.room, function(i, data) {
  $("ul").append("<li>campus: " + this['campusName'] + "</li><li>building: " + this['buildingCode'] + "</li>");
  $.each(data.times, function() {
    $("ul").append("<li>stuff: " + this + "</li>");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请为JSON

尝试以下代码
var data = {
"room":[
    {"campusName":"B",
    "buildingCode":"A",
    "roomNumber":"208",
    "times":[
            "7-8", "9-10"
    ]
    }
]
}

然后你可以使用以下来获得你想要的结果:

data.room[0].campusName; // ==> B
data.room[0].buildingCode; // ==> A
data.room[0].roomNumber; // ==> 208
data.room[0].times; // ==> ["7-8", "9-10"]

<强> EDIT2:

$.each(data.room, function(i) { 
    console.log(data.room[i].campusName);
    console.log(data.room[i].buildingCode );
    console.log(data.room[i].roomNumber );
    console.log(data.room[i].times);
});

<强>输出

B
A
208
["7-8", "9-10"]

<强> EDIT1:

有关详细信息,请访问JSON syntax以及如何访问它。