Reading nested json with jquery returning undefined

时间:2016-04-15 11:17:04

标签: javascript jquery html json nested

I am trying to read a json file with nested elements using jquery and i can call and return the first level, but when i call "result" it returns the result but 5 "undefined" with it also

here is my JSON:

{
"count": 380,
"fixtures": [
{
  "status": "FINISHED",
  "homeTeamName": "Manchester United FC",
  "awayTeamId": 73,
  "matchday": 1,
  "homeTeamId": 66,
  "result": {
    "goalsAwayTeam": 0,
    "goalsHomeTeam": 1
  },
  "date": "2015-08-08T11:45:00Z",
  "soccerseasonId": 398,
  "awayTeamName": "Tottenham Hotspur FC",
  "id": 147075
},
{
  "status": "FINISHED",
  "homeTeamName": "Everton FC",
  "awayTeamId": 346,
  "matchday": 1,
  "homeTeamId": 62,
  "result": {
    "goalsAwayTeam": 2,
    "goalsHomeTeam": 2
  },
  "date": "2015-08-08T14:00:00Z",
  "soccerseasonId": 398,
  "awayTeamName": "Watford FC",
  "id": 147073
}

Here is my HTML and JQuery:

<!DOCTYPE html>
<html>
<head>
    <title> </title>
    <style>
th, td {
border-bottom: 1px solid #ddd;
}
tr:nth-child(even){background-color: #f2f2f2}

</style>
</head>
<body>
      <table id="data">
          <tr>
              <td>status</td>
              <td>team 2</td>
              <td>team 1 </td>
              <td>score team 2</td>
              <td>score team 1</td>
          </tr>


      </table>

   <script     src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
   <script>/*global $*/ /*global result*/
   $.ajax({
       url: 'data.json',
       dataType: 'json',
       type: 'get',
       cache: false,
       success: function(data) {
          $(data.fixtures).each(function(index, value) {

               $("#data").append("<tr><td>"+value.status +"</td>"+"    <td>"+value.homeTeamName+"</td>"+"<td>"+value.awayTeamName+"</td>");
               $.each(value, function(result , v) {

             $("#data").append("<tr><td>"+v.goalsHomeTeam +"</td>"+"<td>"+v.goalsAwayTeam+"</td></tr>");
               });
          });


          }


   });
   </script>
</body>
</html>

and here is the output :

FINISHED    Manchester United FC    Tottenham Hotspur FC
undefined   undefined
undefined   undefined
undefined   undefined
undefined   undefined
undefined   undefined
1   0

I hope i explained it well enough, appreciate any help.

1 个答案:

答案 0 :(得分:1)

JQuery each

看起来你不需要将数组作为第一个参数

$.each(data.fixtures, function(index, value) {

           $("#data").append("<tr><td>"+value.status +"</td>"+"    <td>"+value.homeTeamName+"</td>"+"<td>"+value.awayTeamName+"</td>");

           $("#data").append("<tr><td></td><td>"+value.result.goalsHomeTeam +"</td>"+"<td>"+value.result.goalsAwayTeam+"</td></tr>");

      });

而不是将它放在选择器中