0

I'm having trouble accessing child elements of a JSON file. Here is my JSON file:

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
        }
      }
    }
  }

}];

And I want to access all of the level names. What I want to see is 2 alerts showing: "Tumble in the castle" and "Jungle Rumble". I've tried the following, but it doesn't work. Any ideas? :) Many thanks.

<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>
Andrew Howard
  • 2,818
  • 5
  • 33
  • 59

2 Answers2

1

Try this:

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

The for-loop here is actually iterating over the keys or properties of your levels object. If you want to access the data for that level, you can do this in that loop:

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

jsFiddle Demo

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • Fantastic that did it Cory thank you. I'll list it as the accepted answer when the time limit runs out. Has my JSON file been written in a structured way in your opinion? – Andrew Howard May 06 '14 at 12:42
  • @AndrewJuniorHoward: structurally it seems fine; though I would ditch spaces in the property names and stick with camelCasePropertyNames (`levelDetail['Time Limit']` vs. `levelDetail.timeLimit`, for instance). – Cᴏʀʏ May 06 '14 at 12:45
  • I would not use `for (... in ...)`, though. – PhistucK May 06 '14 at 12:47
  • @andrew: You actually don't have a JSON file, you have a javascript file which declares one variable with a string value that happens to be JSON. In that case there is no reason to use JSON at all. Just directly create the array and object, e.g. `var actualGameData = [{gameBackgroundMusic: ..., ...}];` and remove `var obj = $.parseJSON(...);`. – Felix Kling May 06 '14 at 12:54
  • @FelixKling: Definitely, I did that in my fiddle but forgot to mention it. – Cᴏʀʏ May 06 '14 at 12:55
  • @FelixKling I need to keep it in that structure as JSON doesn't work locally (this is for a phone app). And I need to be able to add levels easily :) – Andrew Howard May 06 '14 at 13:02
  • @andrew: I'm not saying you should change the structure, I'm saying you should create the array directly, without using JSON. Basically just remove the single quotes that delimit the string. It will make it even easier to add new data. See, what you are doing is basically `var json = '[1,2,3]'; var arr = JSON.parse(json);`, which is much easier written as `var arr = [1,2,3];`. – Felix Kling May 06 '14 at 13:05
1

You can grab the level names into an array quickly with Object.keys and then loop over them.

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

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

Demo

Andy
  • 61,948
  • 13
  • 68
  • 95