JSON (JavaScript Object Notation) is a lightweight format used for storing and exchanging data. In JavaScript, there are multiple ways to read and parse JSON files. These methods can be used both in browser environments and in Node.js.
1. Using the fetch() API
The fetch() API retrieves JSON files asynchronously and parses them into JavaScript objects.
Syntax
fetch('sample.json')
.then(response => response.json()) // Parse JSON
.then(data => console.log(data)) // Work with JSON data
.catch(error => console.error('Error fetching JSON:', error));
- Create a sample.json file with the desired data.
- Use fetch("sample.json"), then parse the response with .json().
- Handle the data or display it, using .catch() for errors.
<html>
<head></head>
<body>
<script>
function fetchJSONData() {
fetch('./sample.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Failed to fetch data:', error));
}
fetchJSONData();
</script>
</body>
</html>
//sample.json
{
"users": [
{
"site": "GeeksForGeeks",
"user": "Shobhit"
}
]
}
Output