Splashsky Splashsky - 4 months ago 10
JSON Question

How would I read specifics from a JSON file with jQuery?

I'm trying to make my own tile-based game; a really simple one. I decided to put necessary level data into a JSON file to be read by my primitive attempt at a game engine..

{
"tileset":"main.png",
"layers":[
[
[8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[3 ,3 ,3 ,3 ,2 ,0 ,0 ,0 ,0 ,0 ,0 ],
[1 ,1 ,1 ,1 ,5 ,0 ,0 ,0 ,0 ,0 ,0 ]
], [
[1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
[1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ],
[1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ]
]
]
}


However, I'm a complete newbie to JavaScript and the like, and even jQuery is a tad bit to wrap my head around. How would I read this file and then place each of the layer's jagged arrays into their own variables?

e.g. Take the first layer array and put it into, say,
var first_layer
and so on and so forth

Answer

See this fiddle.

You could use the $.get() function that is a wrapper for the jQuery ajax function. How you process the data is up to you, I'm just punching it out for demonstration purposes.

$.get("/echo/json/", function(data) {
  var data = json; // only for fiddle
  data.layers.forEach(function(layer, index) {
    $("body").append("<ul class=\"list-unstyled layer\" data-index=\"" + index + "\"></ul>");
    layer.forEach(function(row) {
      $(".layer[data-index=" + index + "]").append("<li>" + JSON.stringify(row) + "</li>");
    });
  });
}, "json");

You would need a minor adjustment to your JSON data (the layers would need to be encapsulated in an array or else it is invalid JSON - check online).

You can change the /echo/json/ for the URL of the JSON file on your box. The data assignment would then be unnecessary (I need it because I can't use AJAX in a fiddle).

If you need me to expand on any of the techniques used please ask.