How can I import a JSON file into a variable in JavaScript? I’m trying to load a .json file, but I’m having trouble getting it to work. Everything works fine when I use static data like this:
var json = {
id: "whatever",
name: "start",
children: [{
"id": "0.9685",
"name": "contents:queue"
}, {
"id": "0.79281",
"name": "contents:mqq_error"
}
]
}
However, when I put all that data into a content.json file and attempt to load it into a local JavaScript variable as follows:
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "/content.json",
'dataType': "json",
'success': function(data) {
json = data;
}
});
return json;
})();
I find that the value of the variable json is always null in the Chrome debugger. The content.json file is in the same directory as the .js file that calls it. What did I miss in the process of trying to import the JSON file in JavaScript?