Last Updated : 03 May, 2025
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() APIThe 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));
<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>
JavaScript
//sample.json
{
"users": [
{
"site": "GeeksForGeeks",
"user": "Shobhit"
}
]
}
Output
Using the fetch() API to Read JSON Files 2. Using require() Method in Node.jsIn a Node.js environment, require() is a simple way to read JSON files synchronously.
Syntax
const data = require('./sample.json');
console.log(data);
// Node.js example
const data = require('./sample.json');
console.log(data);
JavaScript
//sample.json
{
"users": [
{
"site": "GeeksForGeeks",
"user": "Shobhit"
}
]
}
Using require() Method in Node.js 3. Using the import Statement for ES Modules
In modern JavaScript (ES Modules), use import ... assert { type: 'json' } to load JSON asynchronously in Node.js (v17+) and supported browsers.
Syntax
import jsonData from './path/to/jsonFile.json' assert { type: 'json' };
console.log(jsonData);
<html>
<head></head>
<body>
<h1>JSON Import Example</h1>
<p>Check your console for fetched data.</p>
<script type="module">
import jsonData from './sample.json' assert { type: 'json' };
console.log(jsonData);
</script>
</body>
</html>
JavaScript
//sample.json
{
"name": "Johina",
"age": 30,
"profession": "Developer"
}
Output
{
"name": "Johina",
"age": 30,
"profession": "Developer"
}
Read JSON File using JavaScript
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4