Node.js Parse JSON using JSON.parse()
Node.js Parse JSON – For parsing JSON data in Node.js, we can use JSON.parse() function of JavaScript Engine.
In this tutorial, we will learn how to parse a given JSON string using JSON.parse(), how to parse a JSON file in Node.js, how to handle invalid JSON safely, and how to access nested values after parsing.
What JSON parsing means in Node.js
JSON parsing means converting a JSON-formatted string into a JavaScript value such as an object, array, string, number, boolean, or null. In Node.js, the standard method for this conversion is JSON.parse(). This method is available globally, so you do not need to install any package to parse a normal JSON string.
For example, a JSON string such as {"name":"John"} is plain text before parsing. After parsing, it becomes a JavaScript object, and you can access name using dot notation or bracket notation.
JSON.parse() syntax in Node.js
The basic syntax of JSON.parse() is shown below.
const parsedValue = JSON.parse(jsonString);
jsonString must be a valid JSON string. If the string is not valid JSON, JSON.parse() throws a SyntaxError. For this reason, JSON parsing in production code is commonly placed inside a try...catch block when the input comes from files, APIs, users, or external systems.
JSON.parse() also supports an optional reviver function. The reviver can transform values while parsing, but beginners usually start with the simple one-argument form.
const parsedValue = JSON.parse(jsonString, reviverFunction);
About JSON format before parsing
- key:value is the building block.
- { } contains an element.
- [ ] contains an array of elements.
- An element can have multiple key:value pairs.
- Value can be a simple value like number or string etc., or an element or an array.
- Elements in an Array could be accessed using index
- Multiple key:value pairs or elements are separated by comma
In valid JSON, object keys and string values must use double quotes. Single quotes, trailing commas, comments, and unquoted keys are not valid JSON. These are common reasons for JSON.parse() errors in Node.js programs.
Example 1 – Node.js JSON Parsing
In this example, we will use JSON.parse() function to parse the string jsonData. Also, we will access the elements from JSON Object using DOT operator.
nodejs-parse-json.js
// json data
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
// parse json
var jsonParsed = JSON.parse(jsonData);
// access elements
console.log(jsonParsed.persons[0].name);
Open a terminal or command prompt and run this script using node command as shown in the following.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js
John
After parsing, jsonParsed is a JavaScript object. The value jsonParsed.persons is an array, so jsonParsed.persons[0] refers to the first person object, and jsonParsed.persons[0].name returns John.
Access parsed JSON values with dot and bracket notation
Once JSON is parsed, you can access values like normal JavaScript object properties. Dot notation is simple when the property name is a valid identifier. Bracket notation is useful when the property name contains spaces, hyphens, or is stored in a variable.
const jsonData = '{"user name":"John","city":"New York","age":30}';
const user = JSON.parse(jsonData);
console.log(user.city); // dot notation
console.log(user["user name"]); // bracket notation
console.log(user["age"]); // bracket notation
Output
New York
John
30
Example 2 – Node.js Parse JSON File
In this example, we shall read a File containing JSON data to a variable and parse that data.
Consider following JSON File. We shall read this file as string to a variable.
sample.json
{
"persons": [{
"name": "John",
"city": "Kochi",
"phone": {
"office": "040-528-1258",
"home": "9952685471"
}
},
{
"name": "Phil",
"city": "Varkazha",
"phone": {
"office": "040-528-8569",
"home": "7955555472"
}
}
]
}
nodejs-parse-json-file.js
// include file system module
var fs = require('fs');
// read file sample.json file
fs.readFile('sample.json',
// callback function that is called when reading file is done
function(err, data) {
// json data
var jsonData = data;
// parse json
var jsonParsed = JSON.parse(jsonData);
// access elements
console.log(jsonParsed.persons[0].name + "'s office phone number is " + jsonParsed.persons[0].phone.office);
console.log(jsonParsed.persons[1].name + " is from " + jsonParsed.persons[0].city);
});
Open a terminal or command prompt and run this script using node command as shown in the following.
Output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json-file.js
John's office phone number is 040-528-1258
Phil is from Kochi
The file example works because fs.readFile() reads the file content and JSON.parse() converts that content into a JavaScript object. In many Node.js programs, it is better to specify the file encoding as utf8 so the callback receives a string directly.
Parse a JSON file in Node.js with utf8 encoding
The following version reads the JSON file as a UTF-8 string, checks for file reading errors, and then parses the JSON content.
const fs = require('fs');
fs.readFile('sample.json', 'utf8', function (err, data) {
if (err) {
console.error('Unable to read file:', err.message);
return;
}
const jsonParsed = JSON.parse(data);
console.log(jsonParsed.persons[0].name);
console.log(jsonParsed.persons[0].phone.office);
});
Output
John
040-528-1258
Handle invalid JSON in Node.js using try…catch
If the JSON string is invalid, JSON.parse() throws an error and the program can stop if the error is not handled. Use try...catch when the JSON data comes from a file, HTTP request, environment variable, queue message, or any external source.
const jsonData = '{"name":"John", "city":"New York",}';
try {
const parsedData = JSON.parse(jsonData);
console.log(parsedData.name);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
Output
Invalid JSON: Expected double-quoted property name in JSON at position 34
The exact error message can differ by Node.js version, but the reason is the same: the JSON string has a trailing comma after the last property. Standard JSON does not allow trailing commas.
Parse JSON request body in Node.js and Express
When working with web applications, you usually do not call JSON.parse() directly on every request body. In Express, the common approach is to use express.json() middleware. It reads the request body, parses JSON, and places the result in req.body.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', function (req, res) {
console.log(req.body.name);
res.send('User received');
});
app.listen(3000);
Use this pattern for normal JSON API request bodies in Express. Use JSON.parse() directly when you already have a JSON string and need to convert it into a JavaScript value.
Use JSON.parse() reviver for date-like values
JSON has strings, numbers, booleans, arrays, objects, and null, but it does not have a native Date type. If a JSON string contains a date value, it is parsed as a string unless you convert it. The optional reviver function can help with this conversion.
const jsonData = '{"name":"John","createdAt":"2026-06-26T10:30:00.000Z"}';
const user = JSON.parse(jsonData, function (key, value) {
if (key === 'createdAt') {
return new Date(value);
}
return value;
});
console.log(user.createdAt instanceof Date);
console.log(user.createdAt.getUTCFullYear());
Output
true
2026
Common JSON.parse() errors in Node.js
| Problem | Example | How to fix it |
|---|---|---|
| Single quotes used in JSON | {'name':'John'} | Use double quotes: {"name":"John"} |
| Trailing comma | {"name":"John",} | Remove the comma after the last property |
| Unquoted object key | {name:"John"} | Quote the key: {"name":"John"} |
| Comment inside JSON | {"name":"John" // user name} | Remove comments from JSON input |
| Parsing an object again | JSON.parse({name:"John"}) | Pass a JSON string, not an already parsed object |
JSON.parse() compared with require() for JSON files
Node.js can also load a local JSON file using require() in CommonJS projects. However, require() caches the loaded file, so it is not suitable when the JSON file changes while the program is running and you need the latest content each time. Reading the file with fs.readFile() and then using JSON.parse() is clearer when you want explicit file reading and error handling.
// CommonJS: loads and parses local JSON, but caches the result
const config = require('./sample.json');
console.log(config.persons[0].name);
For application configuration files that are loaded once at startup, require() can be convenient. For user-uploaded files, frequently updated files, or external JSON content, prefer file reading plus JSON.parse() with error handling.
Security notes when parsing JSON in Node.js
JSON.parse() is safer than evaluating JSON-like text as JavaScript code. Do not use eval() to parse JSON. Even after successful parsing, validate the parsed object before trusting it. A valid JSON document can still contain unexpected fields, missing values, very large arrays, or values of the wrong type for your application.
- Use
try...catchfor external JSON input. - Check required fields before using them.
- Validate data types such as string, number, boolean, object, and array.
- Limit request body size in web applications when accepting JSON from clients.
- Avoid parsing untrusted data and then directly using it in database queries, file paths, or commands.
Node.js JSON.parse() FAQs
Can JavaScript and Node.js parse JSON?
Yes. JavaScript provides the built-in JSON.parse() method, and Node.js supports it globally. You can use it directly without importing a module.
How do I parse a JSON file in Node.js?
Read the file as a string using the fs module, then pass the file content to JSON.parse(). For production code, handle both file reading errors and JSON syntax errors.
Is jQuery.parseJSON deprecated?
Yes. In modern JavaScript, use the native JSON.parse() method instead of jQuery.parseJSON(). Node.js programs should use JSON.parse() for JSON strings.
How do I deserialize JSON in JavaScript?
Deserializing JSON in JavaScript usually means converting a JSON string into a JavaScript value. Use JSON.parse(jsonString) to deserialize a valid JSON string.
Why does JSON.parse() fail for valid-looking JavaScript objects?
JSON.parse() expects valid JSON, not general JavaScript object syntax. JSON requires double-quoted keys and strings, and it does not allow comments or trailing commas.
Node.js Parse JSON QA checklist
- Confirm that every JSON example uses double quotes for keys and string values.
- Check that new Node.js code examples use
language-javascriptand output blocks useoutput. - Verify that file parsing examples explain both reading the file and parsing the file content.
- Make sure invalid JSON handling is shown with
try...catch. - Confirm that the tutorial distinguishes JSON strings from already parsed JavaScript objects.
Conclusion
In this Node.js Tutorial – Node.js JSON File Parsing – we have learnt to parse JSON data from a variable or file using JSON.parse() function with the help of example Node.js programs.
The main point is simple: use JSON.parse() when you have a valid JSON string and need a JavaScript value. When parsing JSON from files, APIs, or users, handle errors, validate the parsed data, and avoid treating JSON-like JavaScript syntax as valid JSON.
TutorialKart.com