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