HOWTO · Node.js
How to Parse Json in Node.js
This tutorial demonstrates how to parse json in Node.js
On this page
JSON parsing turns JSON text into a JavaScript value, such as an object, array, string, number, boolean, or null. In Node.js, use JSON.parse() when you already have the text. For a local JSON file, choose a file-reading method first, then parse the resulting text. The examples below use built-in Node.js modules and create their own temporary input files where needed.
Parse a JSON string with JSON.parse()
Pass JSON text to JSON.parse(). The returned value is ordinary JavaScript data, so you can access its properties and use it in the rest of your program. The input should be JSON text. Passing an already parsed object is usually a mistake: JSON.parse() first coerces its argument to a string, and an ordinary object typically becomes text such as [object Object], which is not valid JSON and causes a SyntaxError. Objects with different string-conversion behavior may produce a different result.
Run this example:
const jsonText = '{"name":"Amina","role":"developer"}';
const person = JSON.parse(jsonText);
console.log(person.name);
JSON.parse() also accepts an optional reviver function, which can transform values as the text is parsed. Most applications do not need a reviver, so omit it unless you have a specific conversion to perform.
Load a local JSON file synchronously
For a small, static configuration file that is loaded once, require() is concise:
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'json-')), 'settings.json');
fs.writeFileSync(file, '{"theme":"dark"}');
const settings = require(file);
console.log(settings.theme);
Loading JSON with require() is synchronous, and Node.js caches the loaded module. If the file changes later in the same process, another require() of that path normally returns the cached value. For data that must reflect file changes, use fs.readFileSync() or fs.readFile() instead. Manually clearing require.cache is possible but usually makes application behavior harder to follow.
Use fs.readFileSync() when the program needs to finish reading a local file before continuing. Provide an encoding such as utf8 to get a string, then call JSON.parse():
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'json-')), 'settings.json');
fs.writeFileSync(file, '{"theme":"dark"}');
const text = fs.readFileSync(file, 'utf8');
const settings = JSON.parse(text);
console.log(settings.theme);
Without an encoding, fs.readFileSync() returns a Buffer, not a string. JSON.parse() expects text, so specify an encoding or convert the buffer with .toString('utf8'). A synchronous read blocks the event loop while the file is being read; it can be appropriate in startup code or a short script, but avoid blocking request handling for slow or large reads.
Read and parse a local JSON file asynchronously
fs.readFile() starts an asynchronous file read and calls its callback when the operation finishes. Check the callback error before parsing so a missing or unreadable file is not passed to JSON.parse():
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'json-')), 'settings.json');
fs.writeFileSync(file, '{"theme":"dark"}');
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
console.error(`Could not read JSON file: ${err.message}`);
return;
}
const settings = JSON.parse(text);
console.log(settings.theme);
});
console.log('Reading has started.');
The file read is asynchronous, so Node.js can continue running other work while waiting for the file operation. JSON.parse() itself remains synchronous: parsing a very large string can still occupy the event loop after the read completes. If parsing fails, the resulting SyntaxError is thrown inside the callback and should be handled there or passed to a suitable error-handling path.
Handle invalid JSON and file errors
File errors and parsing errors have different causes and should be handled separately. A read error means the program did not obtain the text; malformed JSON means it obtained text that does not follow JSON syntax. Do not try to parse when the read callback reports an error.
Wrap JSON.parse() in try...catch when input may be malformed. Catch SyntaxError to report a useful message or apply a recovery policy. Avoid silently replacing bad input with an empty object: that can hide a damaged file and make later failures harder to diagnose. For a synchronous read, handle filesystem errors around the read as well as parse errors around JSON.parse().
This example handles a malformed document after a successful read:
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'json-')), 'settings.json');
fs.writeFileSync(file, '{"theme":}');
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
console.log(`Could not read file: ${err.message}`);
return;
}
try {
JSON.parse(text);
console.log('JSON parsed successfully.');
} catch (error) {
if (error instanceof SyntaxError) {
console.log('The file contains malformed JSON.');
} else {
console.log(`Unexpected error: ${error.message}`);
}
}
});
If the callback receives a filesystem error, report or propagate it and return before parsing. In promise-based code, the same separation applies: handle rejection from the read operation and catch parsing errors where JSON.parse() runs.
Choose an approach for large or changing data
Use JSON.parse() directly for JSON text already in memory. Use require() for small, stable JSON configuration that is loaded once and can use module caching. Use fs.readFileSync() when simple sequential startup work benefits from blocking until the file is available. Use fs.readFile() when the program should continue while file I/O is pending, and check its error argument before parsing.
For very large JSON inputs, reading the entire file and building one complete JavaScript value can consume substantial memory, while parsing a large string is still synchronous. A streaming parser can process suitable formats incrementally, but it adds complexity and may require a package or a format designed for streaming. Choose it when measurement and the data format justify that tradeoff. If a file can change, read it again with a filesystem API when fresh contents are needed; require() caching does not refresh it automatically.