14

I have some sprite sheets with the atlus saved in a JSON format. I'm structuring my atlus based upon the structure from BrowserQuest. Each of their JSON files looks like:

{
    "id": "agent",
    "width": 24,
    "height": 24,
    "animations": {
        "idle_down": {
            "length": 2,
            "row": 0
        }
    },
    "offset_x": -4,
    "offset_y": -8
}

But I'm wondering, how do I even access the data in each JSON file, if it just a raw object literal?

Since each JSON file is an object literal, the only way I could imagine accessing it is to save the object literal to a variable, such as

var agent = {
    "id": "agent",
    "width": 24,
    "height": 24,
    "animations": {
        "idle_down": {
            "length": 2,
            "row": 0
        }
    },
    "offset_x": -4,
    "offset_y": -8
};

I'm hoping there is an easy way to access JSON files.

And because each individual sprite sheet has its own JSON file, I have a large number of files to load.

What is the best way to load such a high number of JSON files? I'm trying to avoid using any JS libraries.

6
  • 1
    $.getJSON? Commented Aug 16, 2013 at 1:11
  • 2
    Trying to avoid JQuery and any JS libraries Commented Aug 16, 2013 at 1:14
  • 5
    Then implement the XHR request yourself and JSON.parse the response. However--quite frankly--that's rather silly when all the work for this and hundreds of other things is already done by jQuery. Commented Aug 16, 2013 at 1:16
  • 2
    You might see the info in the MDN: developer.mozilla.org/en-US/docs/JSON There is a JSON parser built into many modern browsers, as I understand. See also docs.webplatform.org/wiki/apis/json Commented Aug 16, 2013 at 1:17
  • 2
    You can also use a build process to combine (and minify) files for you. That way you can keep them separate for editing, but yet combine them into one blobby when you are ready to run/test the code. To get started, the good old copy command will work. copy file1+file2+file3 bigfile.js Commented Aug 16, 2013 at 1:49

3 Answers 3

12

First, to answer your questions:

But I'm wondering, how do I even access the data in each JSON file, if it just a raw object literal?

JSON stands for JavaScript Object Notation, and as such is identical to how it would be manipulated if it was a JavaScript object.

As for accessing the JSON file if it was a local file, you could use this:

function doStuff(json){
    console.log(json);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
    doStuff(JSON.parse(this.responseText));
});
oReq.open("GET", "http://www.example.com/example.json");
oReq.send();

And then you can just replace doStuff with whatever function handles the JSON.

Sign up to request clarification or add additional context in comments.

5 Comments

What are you doing? You edit an old question, post a bounty and then answer the question yourself. Are you trying to figure out creative ways to get hats?
Try Answer->Edit->Bounty and something like that, no harm in cleaning up old questions in the process
No harm it it... This just strikes me as odd.
I am smelling something fishy here. though i can't say what.
Supersharp, it is better to use eventListeners than onload as you can attach an unlimited number of Event Listeners whereas only one onload, and that you cannot pass a function reference to onload.
7
+50

You can use XMLHttpObject.

Have a look

function getJSONFile(url,callback) {   
  var req = new XMLHttpRequest();
  req.open('GET', url, true); 
  req.overrideMimeType("application/json");
  req.onreadystatechange = function () {
      if (req.readyState == 4 && req.status == "200") {
        callback(req.responseText);
      }
  };
req.send();  
}

use this function like this

getJSONFile('http://www.example.com/example.json', function(data){
  if(data)
    console.log('json data : ' + JSON.stringify(data));
})

Comments

2

You can acheive that with the combination of Promise and XMLHttpRequest to load multiple JSON files in parallel.

This interesting article from HTML5Rocks should help you a lot for download control and optimization as well, for it is comprehensive and functional.

For example, with the get(url) function (from the article above, see source below) returning a JSON object as a Promise:

var names = [ "agent", "arrow", ... ]
var sprites = {}

var all = []
names.forEach( function ( n ) {
  //Request each individual sprite and get a Promise
  var p = get( n + ".json" )
              .then( JSON.parse ) //parse the JSON file
              .then ( function ( sprite ) {
                 //Record the sprite by name
                 sprites[n] = sprite 
                 //Display your sprite as soon as loaded here     
              } )
  //add the promise to an Array of all promises
  all.push( p )
} )

//wait for all the files to be loaded and parsed
Promise.all( all )
    .then( function () {
        //All the  JS sprites are loaded here
        //You can continue your processing
    } )

Source for get(url):

Here is the sample code from HTML5Rocks. It encapsulates a XMLHttpRequest asynchronous call in a Promise:

function get(url) {
  return new Promise(function(resolve, reject) {
    var req = new XMLHttpRequest()
    req.open( 'GET', url )
    req.onload = function() {
      if ( req.status == 200 ) 
        // Resolve the promise with the response text
        resolve(req.response)
      else
        // Otherwise reject with the status text
        reject( Error( req.statusText ) )
    }

    // Handle network errors
    req.onerror = function() {
      reject( Error( "Network Error" ) )
    }

    // Make the request
    req.send()
  } )
}

1 Comment

If you could include a code sample to show the use of Promises, that would be great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.