无法访问JSON子级

时间:2014-05-06 12:30:23

标签: javascript json

我无法访问JSON文件的子元素。这是我的JSON文件:

var actualGameData = '[{
  "gameBackgroundMusic": "background.wav",
  "narratorCongratulations": "congratulations.wav",
  "hitSound": [
    "hit1.wav",
    "hit2.wav",
    "hit3.wav"
  ],
  "narratorHitSound": [
    "narratorhit1.wav",
    "narratorhit2.wav",
    "narratorhit3.wav"
  ],
  "narratorMissSound": [
    "narratormiss1.wav",
    "narratormiss2.wav",
    "narratormiss3.wav"
  ],
  "levels": {
    "Tumble in the Castle": {
      "Time Limit": 60000,
      "Background Image": {
        "Object Name": "backgroundCastle",
        "Image": "backgroundCastle.png"
      },
      "Foreground Image": {
        "Object Name": "foregroundCastle",
        "Image": "foregroundCastle.png"
      },
      "Targets": {
        "Target1": {
          "x axis": 45,
          "y axis": 11
        },
        "Target2": {
          "x axis": 545,
          "y axis": 141
        },
        "Target3": {
          "x axis": 495,
          "y axis": 33
        }
      }
    },
    "Jungle Rumble": {
      "Time Limit": 30000,
      "Background Image": {
        "Object Name": "backgroundJungle",
        "Image": "backgroundJungle.png"
      },
      "Foreground Image": {
        "Object Name": "foregroundJungle",
        "Image": "foregroundJungle.png"
      },
      "Targets": {
        "Target1": {
          "x axis": 465,
          "y axis": 141
        },
        "Target2": {
          "x axis": 525,
          "y axis": 111
        },
        "Target3": {
          "x axis": 405,
          "y axis": 63
        }
      }
    }
  }

}];

我想访问所有级别名称。我想看到的是2个警报显示:“城堡翻滚”和“丛林隆隆声”。我尝试了以下,但它不起作用。有任何想法吗? :)非常感谢。

<html>
    <head></head>
<body>

    <script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript" language="javascript" src="game.json"></script>
    <script>

    $(document).ready(function() {

  var obj = $.parseJSON(actualGameData);
      $.each(obj, function() {
          alert(this['levels.child']);
      });



});
        </script>



    <span></span>
    </body>
    </html>

2 个答案:

答案 0 :(得分:1)

试试这个:

var obj = $.parseJSON(actualGameData);
$.each(obj, function() {
     for (var levelName in this.levels) {
         alert(levelName);
     }
});

这里的for循环实际上是迭代 keys levels对象的属性。如果要访问该级别的数据,可以在该循环中执行此操作:

 for (var levelName in this.levels) {
     alert(levelName);
     var levelDetail = this.levels[levelName];
     var timeLimit = levelDetail['Time Limit'];
 }

jsFiddle Demo

答案 1 :(得分:1)

您可以使用Object.keys快速将级别名称抓取到数组中,然后循环遍历它们。

var levelNames = Object.keys(actualGameData[0].levels);

for (var i = 0, l = levelNames.length; i < l; i++) {
  alert(levelNames[i]);
}

Demo