1

How can I read the following deep level nested json file using jQuery?

{
 "frames": {

"a1-0.png":
{
    "frame": {"x":24,"y":20,"w":12,"h":12},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":50,"y":152,"w":12,"h":12},
    "sourceSize": {"w":256,"h":192}
},
"a1-1.png":
{
    "frame": {"x":0,"y":194,"w":32,"h":44},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":39,"y":121,"w":32,"h":44},
    "sourceSize": {"w":256,"h":192}
},
"a1-2.png":
{
    "frame": {"x":400,"y":194,"w":60,"h":112},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":60,"y":51,"w":60,"h":112},
    "sourceSize": {"w":256,"h":192}
    }
 }
}

Following lines of code of jQuery I'm using to read this. But it's not working. Can somebody help me how to read all of these elements?

Here "a1-0.png" can't be changed because there are 400+ images in a sprite sheet. And this json file represents that sprite sheet. That was made using a software called texture-packer.

jQuery code here:

<button id="FrameNumber">Frame Number</button>
<div id="results"></div>

<script>
$(document).ready(function(e) {
var url="sprite/bounce.json";
     $("#FrameNumber").click(function(){
         $.getJSON(url,function(result){
       $("#results").append('<p>'+result+'</p>');
    });
    });
});
</script>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MFarooqi
  • 1,004
  • 5
  • 12
  • 26

1 Answers1

1

Just use data.frames["name"] to get the data:

$(document).ready(function(e) {
    var url="test.json";

     $("#FrameNumber").click(function(){

         $.getJSON(url,function(data) {
             var f = data.frames["a1-0.png"];
             $("#results").append('<p>x='+f.frame.x+' y='+f.frame.y+'</p>');
            });
    });
});

The format you chose here is optimized for querying frame data. If you want to iterate over all frames use the json array format in TexturePacker. In this case the name of the frame is part of the frame's data and not the key.

Andreas Löw
  • 1,002
  • 8
  • 15
  • Thanks for the solutions.. btw. before reading this answer i've resolved this... this is still really helpful... but instead of using "data.frames["a1-0.png"]... I want to only a quick array like.. data.frames[0], data.frames[1], data.frames[2]... data.frames[n]... is there any solution for that.. Thanks in advance – MFarooqi Feb 23 '12 at 05:02