JSON stores structured data as text. To parse a JSON file in JavaScript, you first read the file contents and then pass the resulting string to JSON.parse(). The method converts the JSON string into a JavaScript value, such as an object or array.
How to Read a JSON File in JavaScript
In Node.js, you can use the built-in node:fs module to read a JSON file from disk.
Read a JSON File Using fs.readFile()
fs.readFile() reads the file asynchronously. The example below reads data.json as UTF-8 text and then parses it with JSON.parse().
Consider the following data.json file:
{
"name": "John Doe",
"age": 32,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}
Use the following index.js file to read and parse it:
const fs = require('node:fs');
fs.readFile('data.json', 'utf8', (error, jsonText) => {
if (error) {
console.error('Could not read file:', error.message);
return;
}
try {
const data = JSON.parse(jsonText);
console.log(data);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
});
Run the script with:
node index.js
Output:
{
name: 'John Doe',
age: 32,
address: { street: '123 Main St', city: 'Anytown', state: 'CA' }
}
fs.readFile() reads the file without blocking the rest of the Node.js process while the file operation completes.
Reading the file and parsing the JSON are separate operations. fs.readFile() can fail if the file cannot be read, while JSON.parse() throws a SyntaxError if the file contains invalid JSON.
Read a JSON File Using fs.readFileSync()
You can also use fs.readFileSync() to read and parse a JSON file synchronously:
const fs = require('node:fs');
try {
const jsonText = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(jsonText);
console.log(data);
} catch (error) {
console.error(error.message);
}
The output is as shown:
{
name: 'John Doe',
age: 32,
address: { street: '123 Main St', city: 'Anytown', state: 'CA' }
}
readFileSync() blocks execution until the file has been read. It can be useful in small scripts or startup and configuration code, but asynchronous file reading is generally preferred when blocking the Node.js process would be undesirable.
Read JSON in the Browser
When loading JSON over HTTP in a browser, you can use fetch() and call response.json(). The json() method reads the response body and parses it as JSON.
Create three files: index.js, data.json, and index.html.
In index.js, add:
fetch('./data.json')
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
In data.json, add:
{
"name": "John Doe",
"age": 32,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}
In index.html, add:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
This method is for JSON served through a web server. Browser-based JavaScript cannot directly read arbitrary local files.
Serve the files locally using http-server:
npx http-server . -p 8000
Then open http://localhost:8000 in your browser.
Open the browser developer tools and select the Console tab. The parsed object appears in the console:
{
name: 'John Doe',
age: 32,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
}
Import a JSON File in Node.js
With CommonJS, Node.js can load a local JSON file directly with require():
const data = require('./data.json');
console.log(data);
The output contains the parsed contents of the JSON file:
{
name: 'John Doe',
age: 32,
address: { street: '123 Main St', city: 'Anytown', state: 'CA' }
}
With ECMAScript modules, current Node.js requires a JSON import attribute:
import data from './data.json' with { type: 'json' };
console.log(data);
Save the file with an .mjs extension, for example index.mjs, and then run it with:
node index.mjs
Alternatively, you can enable ES modules for .js files by adding this to package.json:
{
"type": "module"
}
The with { type: 'json' } import attribute tells Node.js that the imported file contains JSON.
Parse a JSON File Containing an Array
If the JSON file contains an array of objects:
[
{ "name": "John Doe", "age": 32 },
{ "name": "Joe Doe", "age": 30 },
{ "name": "Alice", "age": 28 }
]
Use JSON.parse() as shown:
const fs = require('node:fs');
fs.readFile('data.json', 'utf8', (error, jsonText) => {
if (error) {
console.error('Could not read file:', error.message);
return;
}
try {
const people = JSON.parse(jsonText);
people.forEach((person) => {
console.log(`${person.name} is ${person.age} years old`);
});
} catch (error) {
console.error('Invalid JSON:', error.message);
}
});
Output:
John Doe is 32 years old
Joe Doe is 30 years old
Alice is 28 years old
The script parses the JSON array and then iterates over it to print each person's name and age.