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;
    });
};

2 Answers 2

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);
    });
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
The solution I realised is to use a call to $.ajax() and ensure async: false is set.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.