I’m trying to load a local JSON file, but it’s not working. Here’s my JavaScript code (using jQuery):
var json = $.getJSON("test.json");
var data = eval("(" + json.responseText + ")");
document.write(data["a"]);
The test.json
file contains:
{"a" : "b", "c" : "d"}
However, nothing gets displayed, and Firebug shows that data
is undefined. I can see json.responseText
in Firebug, and it looks fine. The issue is, when I copy the line:
var data = eval("(" + json.responseText + ")");
into Firebug’s console, it works fine, and I can access data
.
What’s the best way to properly javascript load json file?
You can use fetch() – the modern way :
fetch('test.json')
.then(response => response.json())
.then(data => {
console.log(data.a); // "b"
});
This is the cleanest and most modern way to handle the javascript load json file problem.
The key is knowing that fetch() is asynchronous, so you have to use .then() to wait for the file to load before accessing it.
Use XMLHttpRequest – old school but works :
var xhr = new XMLHttpRequest();
xhr.open('GET', 'test.json', true);
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data.a); // "b"
}
};
xhr.send();
If you prefer the old way or need support in older environments, this one’s still solid. Just remember to avoid using eval()—JSON.parse() is safer and faster for your javascript load json file needs.
If you’re working in Node.js (not browser) :
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('test.json', 'utf8'));
console.log(data.a); // "b"
If your goal is to javascript load json file from the local filesystem outside of the browser (say, in a Node.js script), this is your go-to solution.