0

So i'm grabbing json with a function and then returning it to multiple functions that are asking for json data

function getJSON(){
        var jsonData;
        jsonData = $.getJSON("../assets/json-feed/file.json", function(json){
            jsonData = json.data; //removes initial {} capsulation
            return jsonData;
        });
        return jsonData;
    }

When I perform the inner return, the object in console log is Object {readyState: 1} and I have to dig another level down to a key called responseJSON: Object to find my data. I am expecting Object {name: "Important title name", mod: "long number", key1: Object, key2: Object, key3: Object…} rather than the former format.

How can I avoid this change in object structure, or is this something that always happens on returns of objects? Is there a more efficient way to return an object that retains the original structure?

1 Answers1

0

An Async function (getJSON), cant be handled synchronously. The Async way:

function getJSON(callback){
    $.getJSON("../assets/json-feed/file.json", function(json){
        callback(json.data); //removes initial {} capsulation
    });
  }

Use like this:

getJSON(console.log);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151