我已经完成了有关JSON的Lynda课程,并且确实四处搜寻以解决此错误;但是,我想我的问题太具体了,我需要一个例子。
JSON格式
{
"date": "2017-10-15",
"league": "NHL",
"odds": "spreads",
"status": "200 OK",
"updated": "2017-10-23 00:07 UTC",
"games": [
{
"away": {
"rot": "051",
"odds": {
"acesport": "-1.5 +178",
"betphoenix": "-1.5 +177",
"betus": "-1.5 +170",
"bookmaker": "-1.5 +180",
"bovada": "-1.5 +170",
"dsi": "-1.5 +170",
"easystreet": "-1.5 +180",
"jazz": "-1.5 +175",
"mirage": "-1.5 +180",
"open": "-1.5 -110",
"pinnacle": "-1.5 +192",
"sbg": "-1.5 +175",
"sia": "-1.5 +150",
"sportsbet": "-1.5 +240",
"station": "-1.5 +175",
"westgate": "-1.5 +175"
},
"team": "Boston Bruins",
"score": 1
},
"home": {
"rot": "052",
"odds": {
"acesport": "+1.5 -208",
"betphoenix": "+1.5 -217",
"betus": "+1.5 -200",
"bookmaker": "+1.5 -210",
"bovada": "+1.5 -200",
"dsi": "+1.5 -200",
"easystreet": "+1.5 -210",
"jazz": "+1.5 -205",
"mirage": "+1.5 -220",
"open": "+1.5 -110",
"pinnacle": "+1.5 -214",
"sbg": "+1.5 -210",
"sia": "+1.5 -175",
"sportsbet": "+1.5 -280",
"station": "+1.5 -210",
"westgate": "+1.5 -200"
},
"team": "Vegas Golden Knights",
"score": 3
},
"time": "7:05 PM EST",
"status": "Final"
}
]
}
从搜索和视频中收集的信息来看,我认为下面的代码已经接近。问题一定是这个inst只是数组中的值,而是另一个对象?
for (i = 0; i <= body.games.length; i++){
for (var key in body.games[i]) {
console.log("Game " + (i +1));
console.log(body.games[i][key].away.odds.acesport);
}
}
最佳答案
您的帖子没有问题。我将假设以下问题:“如何访问数组中的对象?”和“为什么我的代码不起作用?”。
也许这个例子会为您澄清。
for (var i = 0; i <= body.games.length; i++) {
var game = body.games[i];
console.log("Game number " + (i + 1));
console.log(game.away.odds.acesport);
for (var key in game) {
// This will print the strings "away", "home", "time" and "status",
// but not the values game[key] which are "object", "object",
// "7:05 PM EST" and "Final".
console.log("Game property: " + key);
}
}
关于javascript - 访问数组中的JSON对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46881024/