You can read JSON files in JavaScript using Fetch API or AJAX or import statement. Fetch API is a standard method we can use to read a JSON file either a local file or one uploaded to a server.
Read JSON file JavaScript example
Simple HTML example code.
file.json
{
"id": 1,
"title": "Hello World",
"completed": false
}
Using the XMLHttpRequest
object to make a request to the file, and then parse the JSON data using the JSON.parse()
method.
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Open a new connection to the JSON file
xhr.open('GET', 'path/to/file.json', true);
// Set the response type to JSON
xhr.responseType = 'json';
// When the request has loaded
xhr.onload = function() {
// If the request was successful
if (xhr.status === 200) {
// Parse the JSON data
var jsonData = JSON.parse(xhr.responseText);
// Use the JSON data as needed
console.log(jsonData);
}
};
// Send the request
xhr.send();
Output:
You can also use the Fetch API to read a JSON file in JavaScript. The Fetch API provides a modern, promise-based way to make network requests and handle responses.
fetch('path/to/file.json')
.then(response => response.json())
.then(jsonData => {
// Use the JSON data as needed
console.log(jsonData);
})
.catch(error => {
// Handle any errors that occurred
console.error(error);
});
Use AJAX (Asynchronous JavaScript and XML) to read a JSON file in JavaScript. AJAX allows you to make asynchronous requests to a server without reloading the entire page.
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Open a new connection to the JSON file
xhr.open('GET', 'path/to/file.json', true);
// Set the response type to JSON
xhr.setRequestHeader('Content-Type', 'application/json');
// When the request has loaded
xhr.onreadystatechange = function() {
// If the request was successful
if (xhr.readyState === 4 && xhr.status === 200) {
// Parse the JSON data
var jsonData = JSON.parse(xhr.responseText);
// Use the JSON data as needed
console.log(jsonData);
}
};
// Send the request
xhr.send();
In all examples, replace path/to/file.json
with the actual path to your JSON file.
Do comment if you have any doubts or suggestions on this JS JSON file topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version