JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In this blog post, we will discuss how to load a JSON file in JavaScript.
Using XMLHttpRequest
To load a JSON file in JavaScript, you can use the XMLHttpRequest object, which is a built-in browser object that allows you to request data from a server.
Here’s an example of how you can use the XMLHttpRequest object to load a JSON file:
function loadJSON(filePath, callback) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open("GET", filePath, true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == "200") {
callback(JSON.parse(request.responseText));
}
};
request.send(null);
}
loadJSON("data.json", function(data) {
console.log(data);
});
In the example above, the loadJSON function takes two parameters: the file path and a callback function. The callback function will be executed once the JSON data is successfully loaded and parsed.
Using Fetch API
The Fetch API is a more modern and easier way to make web requests and handle responses than the XMLHttpRequest. It is built into the modern browsers and returns a promise that resolves with the Response to that request, whether it is successful or not.
Here’s how to use the Fetch API to load a JSON file:
function loadJSON(filePath) {
return fetch(filePath)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
});
}
loadJSON("data.json")
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error while fetching JSON file:", error);
});
In this example, the loadJSON function returns a promise that resolves with the parsed JSON data. To use the function, you can simply call it with the desired file path and then use the .then() method to handle the parsed data, and the .catch() method to handle any errors.
Conclusion
As you can see, loading a JSON file in JavaScript can be done using either the XMLHttpRequest object or the Fetch API. While both methods work, the Fetch API is more modern and provides a cleaner syntax, making it the recommended approach for most applications.