Cannot read property of some JSON objects

I am writing a simple script that will display Major League Baseball scores via the MLB API. I'm pulling in the master scoreboard json file and accessing some of the values. It was all working great until I started accessing the actual scores of the games which are nested objects in the JSON file.

Here is what I have:

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?

If I simply comment out the homeScore and awayScore variables the missing games (such as the Dbacks vs Cubs game) reappear.

I am getting an error:

Uncaught TypeError: Cannot read property 'r' of undefined

But when I use a JSON viewer the object linescore.r looks the same as any other game and if I change the i variable to 7 (the id for the dbacks game) and remove the i++ it shows the correct values for the dbacks game.

You can find a link to the codepen here: http://codepen.io/erwstout/pen/wGppOV

Thanks!

Answers 1

  • It seems some data does not contain linescore. You need to check the property before use it.

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

Related Articles