To read a JSON file from a URL using JavaScript, you can use the XMLHttpRequest
or fetch
API. Here’s an example using both methods:
1. Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json', true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
var data = xhr.response;
// Process the JSON data further
console.log(data);
}
};
xhr.onerror = function() {
console.error('Error:', xhr.statusText);
};
xhr.send();
2. Using fetch:
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => {
// Process the JSON data further
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
In both cases, we initiate a GET request to the specified URL (https://example.com/data.json
). The response from the server is handled in the onload
callback for XMLHttpRequest or in the promise chain for fetch.
If the request is successful (status code 200), we can access the JSON data using xhr.response
for XMLHttpRequest or the parsed JSON data in the second then
block for fetch. In the examples, we simply log the data to the console, but you can perform further processing or manipulate it as needed.
If an error occurs during the request, the onerror
callback for XMLHttpRequest or the catch
block for fetch will handle the error and log it to the console.
JavaScript read JSON files from URL example
Simple example code that demonstrates how to read a JSON file from a URL using the fetch API in JavaScript:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
console.log(data);
// Process the JSON data further
console.log('User ID:', data.userId);
console.log('Title:', data.title);
console.log('Body:', data.body);
})
.catch(error => {
console.error('Error:', error);
});
Output:
In this example, we fetch a JSON file from the URL 'https://jsonplaceholder.typicode.com/posts/1'
, which is a fake REST API that provides sample data. The response from the server is converted to JSON using the response.json()
method.
If any error occurs during the fetch request or JSON parsing, the catch
block will handle the error and log it to the console.
Comment if you have any doubts or suggestions on this Js Json topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version