0

I am in the middle of writing up some Jquery and the order of my code is not behaving in the way I want. Specifically, I am making a JSON call(getJSON) and once I get the file, I would like to create an array which I will later use.

My code -

jQuery(document).ready( function () {
    console.log("first");
    var things = [];
    jQuery.getJSON("file.json", function(data) {
        jQuery.each(data, function(key, value) {
            jQuery.each(value, function(i, v) {
                console.log("i = " + i  + " v = " + v);
                things.push(v);
            });
        });
        console.log( "things(JSON) = " + things);
    });
    console.log( "things = " + things);
    console.log("last");
});

My JSON file -

{
    "good": [
        "icecream",
        "perl",
        "baskets"
    ],
    "bad": [
        "greenLantern",
        "villians"
     ],
}

I expected this order of execution: getJSON, get data from JSON object, add to array "things".

But instead I see this:

first

GET test2.json

things(LAST) =

last

i = 0 v = icecream

i = 1 v = perl

i = 2 v = baskets

i = 0 v = greenLantern

i = 1 v = villians

things(JSON) = icecream,perl,baskets,greenLantern,villians

This order jumbling does not allow me to create my array with the values I want. Instead I end up with an empty array. Can someone please shed light on what's going on?

Thank you.

user1684636
  • 91
  • 1
  • 5

0 Answers0