Ich versuche, durch JSON-Datei durchforsten alle Daten und packe es in eine Variable, damit ich es in anderen Komponenten verwenden kann. Der Code, den ich geschnappt habe, funktioniert gut für das Parsen durch die JSON-Datei. Auf Zeile 22, console.log(data)
druckt alle Objekte in Json ohne ein Problem, jedoch auf Zeile 27, console.log(data)
druckt undefined. Jede Hilfe würde sehr geschätzt werden, Danke.JSON-Datei lädt nur in der Funktion, aber sobald fertig sind die geladenen Daten in React
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;