-2

I am building a sports site and need to acccess the json data that is accessible from http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json . On my page I am trying to get this data from an ajax. Here is my script below.

<div id="data"></div>

<script>
    $.ajax({
       url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
       dataType: 'json',
       success: function(data) {
          var items = [];

          $.each(data, function(key, value) {

            $('#data').html(value);

          });

        },
    });
</script>

When I do this i just get "261" on my page. I had assumed i would see all the values. A lot of this data is nested and everything I read was just saying to do something like the script I have above. There are tons of different keys and values and I'll be trying to get select ones in the future. I have tried var variable = data.home.score; but that just got blank results..

Here is an example of some of the data when indented.

"home":{  
     "score":{  
        "1":0,
        "2":10,
        "3":7,
        "4":0,
        "5":0,
        "T":17
     },

Am I going about getting this data completely wrong? Can anyone help me get on the right path? Any insight or link's to answers that may help me would be much appreciated.

Phil
  • 157,677
  • 23
  • 242
  • 245
Ryne
  • 1,195
  • 2
  • 14
  • 32
  • You want to see **all** the values? Try `
    ` instead of a `
    ` and use `$('#data').text(JSON.stringify(data, null, 2))`
    – Phil Nov 28 '17 at 03:01
  • 2
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Phil Nov 28 '17 at 03:02

1 Answers1

1

The JSON from the URL looks like the following, but I have shortened it for better readability.

{
  "2012020500": {
    "home": {
      "score": {
        "1": 0,
        "2": 10,
        "3": 7,
        "4": 0,
        "5": 0,
        "T": 17
      },
          "abbr": "NE",
.....
.....
.....
},
  "nextupdate": 261
}

The following loop reads key-value pairs from the received JSON and populates the value in '#data' . So for each element it replaces the old one. Since 261 is the last value, it is intact.

$.each(data, function(key, value) {
    $('#data').html(value);
});

In order to print all the values in a node, it is required to dynamically create elements.

$.each(home, function(key, value) {
    $('#data').append("<div>"+value+"<div>");
});

To get the scores, need to fetch the 'score' node and read the values like the following.

$.ajax({url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
    dataType: 'json',
    success: function(data) {
        var score= data["2012020500"].home.score;
        $.each(score, function(key, value) {
            $('#data').append("<div>"+key+" - "+value+"<div>");
        });
    }
});