无法读取某些JSON对象的属性

时间:2016-04-08 06:33:49

标签: javascript jquery json

我正在编写一个简单的脚本,通过MLB API显示美国职业棒球大联盟得分。我拉入主记分板json文件并访问一些值。在我开始访问JSON文件中嵌套对象的游戏的实际分数之前,这一切都很有效。

这就是我所拥有的:

var mlb = 'http://mlb.mlb.com/gdcross/components/game/mlb/year_2016/month_04/day_07/master_scoreboard.json';

i = 0;

$.ajax({
  url: mlb,
  dataType: 'json',
  success: function(data){

    var games = data.data.games.game;

    $.each(games, function() {
      var home  = games[i].home_team_name,
          away  = games[i].away_team_name,
          venue = games[i].venue,
          homeScore = games[i].linescore.r.home,
          awayScore = games[i].linescore.r.away;

         $('<p>' + home + ' vs ' + away + ' - ' + venue + '</p>').appendTo('#scoreboard');
         $('<p>' + homeScore + ' - ' + awayScore + '</p>').appendTo('#scoreboard');
         i++;
      });
     }
    });

    // why is the dbacks (game 7) game not showing when linescores are displayed?

如果我只是注释掉homeScoreawayScore个变量,则会重新出现丢失的游戏(例如Dbacks vs Cubs游戏)。

我收到错误:

Uncaught TypeError: Cannot read property 'r' of undefined

但是当我使用JSON查看器时,对象linescore.r看起来与任何其他游戏相同,如果我将i变量更改为7(dbacks游戏的ID),移除i++它会显示dbacks游戏的正确值。

您可以在此处找到指向codepen的链接:http://codepen.io/erwstout/pen/wGppOV

谢谢!

2 个答案:

答案 0 :(得分:1)

Indians vs Red Sox - Progressive Field 似乎没有一个linecore值。先检查一下。您还可以在回调中使用迭代器和值参数,而不是递增i

很好的饲料。

&#13;
&#13;
var mlb = 'http://mlb.mlb.com/gdcross/components/game/mlb/year_2016/month_04/day_07/master_scoreboard.json';
$.ajax({
    url: mlb,
    dataType: 'json',
    success: function(data){

        var games = data.data.games.game;

        $.each(games, function(i,v) {
            var home  = v.home_team_name,
                away  = v.away_team_name,
                venue = v.venue,
                homeScore, 
                awayScore;
            if(v.linescore){
                homeScore = v.linescore.r.home,
                awayScore = v.linescore.r.away;         
            } else {
                homeScore = "n/a",
                awayScore = "n/a";          
            }
            $('<p>' + home + ' vs ' + away + ' - ' + venue + '</p>').appendTo('#scoreboard');
            $('<p>' + homeScore + ' - ' + awayScore + '</p>').appendTo('#scoreboard');
        });
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=scoreboard></div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

似乎有些数据不包含linecore。您需要在使用之前检查该属性。

 homeScore = games[i].linescore ?jQuery.parseJSON(games[i].linescore.r.home): {},
 awayScore = games[i].linescore ?jQuery.parseJSON(games[i].linescore.r.away) : {};