0

I am trying to read a JSON file into a global array of objects. The code works except I cannot seem to find a way to get the data out of the Ajax $.getJSON call into the global variable. Maybe this is because of scope and or synchronisation.

I have tried a few approaches and I am using the following code to read in a JSON file (See Using Jquery to get JSON objects from local file):

var questions = {};

$(document).ready(function() {

    readJsonFile().done(function (questions) {
        // This outputs the array of objects (questions) OK ->
        console.log("Questions read from JSON file: " + questions);
    });

    // Cannot read from the array here
    console.log("Question 1: " + questions[0].question);

...

function readJsonFile() {
    return $.getJSON("questions.json").then(function (data) {
        // This was in the original post and didn't seem to return the array
        // return data.items;
        return data;
    });
};
Community
  • 1
  • 1
pcrx20
  • 103
  • 1
  • 4
  • 12

2 Answers2

1

The first console log outputs the parameter of the callback. The second outputs the global object. There is no connection between them other than the fact that they are similarly named. You should do something like this:

 readJsonFile().done(function (data) {
        questions = data; // <- assigned the return data to the global object
        // This outputs the array of objects (questions) OK ->
        console.log("Questions read from JSON file: " + questions);
    });
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • Thanks. But I still get 'Cannot read property 'question' when outputting questions[0].question outside of the call to readJsonFile. Also in the console window this error appears before the Ajax call completes. Is this due to async loading? – pcrx20 Sep 27 '13 at 09:16
  • Yes. The second console log is executed immediately after the the Ajax call is made, before the response returns, so before the callback is executed. – Tibos Sep 27 '13 at 09:21
  • The solution I realised is to use a call to $.ajax() and ensure async: false is set. – pcrx20 Sep 27 '13 at 10:13
0

Ok. I worked out how to do this... To load the JSON file synchronously use the following code:

function readJsonFile() {
    $.ajax({
        type: 'GET',
        url: 'questions.json',
        dataType: 'json',
        success: function(data) {
            questions = data;
        },
        async: false
    });
};

After a call to this function, my global variable 'questions' is accessible since the callback waits until the response is completed. Clearly you would want to do some error checking if Ajax call was not successful.

pcrx20
  • 103
  • 1
  • 4
  • 12