我有这个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>")
});
});
});
});
答案 0 :(得分:0)
data.times
的元素只是字符串,而不是对象,所以你不应该为它们编制索引。它应该只是:
$.each(data.times, function() {
$("ul").append("<li>stuff: " + this + "</li>");
});
此外,您的第一个$.each()
回调中的参数列表是错误的。它应该是function(i, data)
- 第一个参数是数组索引(或者对象属性名称,如果你在对象上进行迭代),第二个参数是值。
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;
答案 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以及如何访问它。