Reputation: 2535
I am trying to parse through JSON file grabbing all its data and put it into a variable so I can use it in other components. The code I grabbed works fine for parsing through json file. On line 22, console.log(data)
prints out all the objects in json without an issue, however on line 27, console.log(data)
prints out undefined. Any help would be greatly appreciated, Thanks.
var jsonData = require('../../../../file.json');
var data;
function loadJSON(jsonfile, callback) {
var jsonObj = new XMLHttpRequest();
jsonObj.overrideMimeType("application/json");
jsonObj.open('GET', "../../file.json", true); //asynchronous because true
jsonObj.onreadystatechange = function () {
if (jsonObj.readyState == 4 && jsonObj.status == "200") {
callback(jsonObj.responseText);
}
};
jsonObj.send(null);
}
function load() {
loadJSON(jsonData, function(response) {
data = JSON.parse(response);
//line 21
console.log(data);
});
}
load();
//line 27
console.log(data);
const JSONLoad = data;
module.exports = JSONLoad;
Upvotes: 0
Views: 38
Reputation: 3163
The AJAX call is asynchronous so console.log(data)
will be called immediately after load()
, before the request receives data.
Upvotes: 1