Quanquan Liu
Quanquan Liu

Reputation: 1477

Using data results immediately after loading from JSON file

I'm having a bit of trouble using data loaded from a JSON file immediately after I load it. Code below.

newdata = []

$.getJSON(file, function(data) {
            $.each(data.items, function(i,item){
            if (item.id != undefined) {
                if (item.id === cl) {
                    newdata.push(item.id);
                }
            }
            });
        });

console.log(newdata);

The console.log statement doesn't return the data though, it returns an empty array []. However, if I call the variable data in my chrome debugger, it returns the correct array. How do I use data with the correct elements immediately after I create it from the JSON file?

Upvotes: 0

Views: 101

Answers (3)

Quanquan Liu
Quanquan Liu

Reputation: 1477

Another method is:

$.ajaxSetup({
    async: false
});

But after being pointed out that the method is deprecated and the better way to do this is given by melc and Thomas Upton.

Upvotes: 0

Thomas Upton
Thomas Upton

Reputation: 1899

jQuery.getJSON is asynchronous. You should read the documentation on it to become familiar with how its success callback works.

The function that receives the JSON data is called on success, but the actual $.getJSON function returns immediately and execution continues. So, in practice, this means that your console.log(data) gets executed before the JSON data comes back, but by the time you log it manually in the Chrome console, the data has been retrieved.

The jQuery AJAX methods also return objects that implement a promise-like API, so you can use that, too.

There are many, many questions about this topic on both Stack Overflow and other resources.

The following code uses both the success function argument and the Deferred object methods. You can do whatever you want with your data in the handleData function.

function handleData(data) {
    // you can do whatever you want with your data here
    console.log(data);
}

function formatData(data) {
    var formatted = [];
    $.each(data.items, function(i,item){
        if (item.id != undefined) {
            if (item.id === cl) {
                formatted.push(item.id);
            }
        }
    });
    return formatted;
}

$.getJSON(file, formatData).done(handleData);

Upvotes: 0

melc
melc

Reputation: 11671

Should be written like this,

newdata = []

$.getJSON(file, function(data) {
            $.each(data.items, function(i,item){
            if (item.id != undefined) {
                if (item.id === cl) {
                    newdata.push(item.id);
                }
            }
            });
              console.log(newdata);
        });

Upvotes: 1

Related Questions