我正在尝试从我创建的JSON文件中访问此数据:
{
"game":"one",
"schedule":[
{
"day":"mon",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"tue",
"start":"00:00:00",
"end":"05:30:00"
}
],
"game":"two",
"schedule":[
{
"day":"mon",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"wed",
"start":"00:00:00",
"end":"05:30:00"
}
],
"game":"three",
"schedule":[
{
"day":"fri",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"thu",
"start":"00:00:00",
"end":"05:30:00"
}
]
}
这就是我尝试访问它的方式:
$.getJSON(json_location, function(data) {
$.each(data.schedule, function() {
console.log(this.day + " " + this.start + " " + this.end);
});
});
然而,这只返回游戏三中的值 - 所以:fri 00:00:00 05:30:00,周六00:00:00 05:30:00。理想情况下,我希望能够迭代第一场比赛,然后是两场比赛,然后是三场比赛。但无论我尝试调整代码多少,我都不允许$ .getJSON访问数据。
我也知道这种格式可以与javascript一起使用,但是根据RFC 4627(JSON规范)无效 - 所以任何有关如何改进JSON布局的建议都将非常感激。
答案 0 :(得分:2)
你是对的,这个JSON是错误的,因为相同的键游戏和日程安排有多个值
尝试这样的事情(最简单的改变)
{
"one":[
{
"day":"mon",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"tue",
"start":"00:00:00",
"end":"05:30:00"
}
],
"two":[
{
"day":"mon",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"wed",
"start":"00:00:00",
"end":"05:30:00"
}
],
"three":[
{
"day":"fri",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"thu",
"start":"00:00:00",
"end":"05:30:00"
}
]
}
然后像
一样迭代它for ( var gameId in data )
{
var scheduleArray = data[ gameId ];
//iterate this array
}
答案 1 :(得分:1)
您的JSON数据错误。您有3个计划项目,而不是包含计划的3个对象
[ // array of games
{ // first game and schedule
"game":"one",
"schedule":[
{
"day":"mon",
"start":"00:00:00",
"end":"05:30:00"
},
{
"day":"tue",
"start":"00:00:00",
"end":"05:30:00"
}
]
},
{ // second game and schedule
"game": "two",
"schedule": [
..
]
},
etc
]
答案 2 :(得分:1)
看起来您已在对象的顶层各自定义了"game"
和"schedule"
三次。只需修改你的JSON就可以了:也许你应该有一组游戏对象,每个游戏对象都有一个"number"
和一个"schedule"
字段。
答案 3 :(得分:0)
将您的json代码传递到此站点并正确格式化。 http://json.parser.online.fr/