JSON advice for projects

Hi i am currently doing the JSON projects and having success however i was wondering does any interaction with JSON data have to always be inside the json function :

$.getJSON("myAPI", function(json) {
//all my code 
};

I would like to save the data into a global variable, is this possible?

Thanks

Absolutely… JSON is an object so just assign it to a variable and use it as you wish! :wink:

1 Like

You could do something like this:

var myData;
$.getJSON("myAPI", function(json) {
  myData = json;
};

This way other function could also use the JSON that is coming back. The “problem” is that getJSON is asynchronous, so you would have to wait for it to be fetched.

So you can assign it to a variable, but you can only use it after the callback is fired (that is: when function(json) is run).

1 Like

Yes, it has to be inside the json function, because it’s a callback. getJSON is a function that someone just like you made, it isn’t code much different from yours, thus it follows the same rules as your code. It cannot access data outside of it’s environment.
The json function is just a parameter that you send, you see? You could send $.getJSON("parameter1", "parameter2"){} but instead you choose to send in an anonymous function(which is just a function without a name, declared on the spot). This anonymous function is just a parameter, just like a string or a number. This callback function is used by the person who made this getJSON code, and is executed after the JSON data is retrieved.

You could, for example, create a function helloJSON(arguments){}, and send in $.GETJSON("parameter1", helloJSON) and things would work the same way, because you’re still passing in a function that will be called after execution.

As for storing data in global variables, sure you can, just make the assignment.

var my_variable = "";

$.getJSON("myAPI", function(json) {
    my_global_variable = json;
};
1 Like
var my_variable = "";
$.getJSON("myAPI", function(json) {
my_global_variable = json;
};
 console.log(my_variable);

so this would put my json data into the console ?

that would log “” because console.log() would be run before the callback, since $.getJSON() is an asynchronous operation.

you should put console.log inside the callback

Not really, because $.getJSON is an asynchronous function, it doesn’t execute like the rest of your code. It executes “in parallel”(not really but kinda).

So, when you try to console.log the variable, it will still be “”, because the json has to make the request through the internet, get the data back, parse it and only then give the value to your variable.

Your console.log will execute before that happens, because the function is asynchronous, you see? That’s why ideally you don’t make assignments like that, you can’t really on your internet and processing speed to get the information back.

So if i refer to my_variable outside of the callback it will always result in “” meaning i cannot use the JSON data out side of the callback?

You can in various different ways, you can lock your code to only continue executing after the callback is received, or use various async libraries to do that for you. But, the code as you’ve pasted it won’t work that way naturally, without some preparation.

Ok great so I need to learn what code has priority over others when run in the browser

It’s not exactly about priority, but when you make a json call you’re visiting a thing on the internet, it’s a download. So it won’t be downloaded instantly like your code is executed. You have to wait for the download to finish and the data to be passed, that’s why we have a callback, the callback will only be executed after this process is over and the data is ready to be used.

So there is no priority unless stated i.e. Run this code once this has loaded(I have not learnt yet) it will run whatever is quicker

I.e. Console log is quicker than gathering data for json

Imagine that your code is walking in a straight like.
Async code is like going out of that line and saying “go do this other thing for me, while i’ll keep on walking on the straight line”.
Most code is synchronous, if you want to leave the line you can’t ask someone to do something for you, you must leave the line. Synchronous code locks the execution until it’s processing is over. Asynch doesn’t lock, so console.log is executed first, not because it’s quicker but because other work is being done by the asynch portion.

I think the question here is why do you need to save the data into a global variable?

The whole reason of the callback is that you can only interact with the data once you get it, so you should structure you code accordingly and figure out what can be done synchronously, and what can only be done in callbacks.

For readability and ease, jQuery AJAX calls does return deferred object, which provide some chain commands like .done(), .catch(), .fail()…etc.

1 Like

var myData;
I think this confused you a bit …

$.getJSON(“myAPI”, function(json) {
myData = json;
here you can use the global myData
};
myData … oops
out here you cant … reason being … when you run your code you set myData code continues to run … getJSON is called but has to wait for a reply/response … code continues … outside myData … reply/response not back yet so myData still === “” … then getJSON gets reply/response so inside the getJSON you can now use the global myData …

As others have said, you can assign the results from an asynchronous callback to a global variable, you just need to be careful about when you can use the results. This might be a little advanced depending on your background but understanding the event loop, particularly the “run to completion” rule will best help you understand what runs when. (Event Loop on MDN). Asynchronous callbacks essentially put another function on the queue when they are ready.

HTML:
<button onclick=“getData()”> Call $.getJSON</button>
<button onclick=“displayMyGlobal()”>Display JSON Data I stored in a global variable</button>
JS:

var myGlobal; 

function getData() {
    $.getJSON("myAPI", function(json) {
    myGlobal = json;
    //all my code 
    });

    console.log(myGlobal);
};


function displayMyGlobal() {
    alert(JSON.stringify(myGlobal));
}

So what happens here? If you click the first button, the anonymous function you pass to $.getJSON is being passed to it but it isn’t being run yet, and the current stack runs to completion, so it will just execute the next statement, logging undefined to the console. When you click the second button, you will see the JSON data you retrieved as an alert. This second function will be accessing the global variable myGlobal, which was set by the callback. If you click the second button before you click the first button, of course you will see undefined since you didn’t retrieve the data yet.

At the risk overexplaining, even if you change getData to the following you will still log undefined to the console:

function getData() {
    setInterval(function() { myGlobal = { data: 1 }; }, 0);
    console.log(myGlobal);
};

Here we aren’t even using the network, and the timeout is 0, but you will still see undefined on the console since the current frame runs to completion. Such is the nature of asynchronous callbacks and the event loop.

One last aside: not all callbacks in Javascript are asynchronous, but anything involving AJAX surely will be. An example of a synchronous callback would be the Array.map function.