JSON.parse() in Node.js
Learn how JSON.parse() converts JSON-formatted text into JavaScript values. Understand its syntax, working, objects, arrays, nested JSON data, error handling, and practical Node.js programs with expected outputs.
1. What Is JSON.parse()?
JSON.parse() is a built-in JavaScript method
used to parse a valid JSON string and convert it into the
corresponding JavaScript value.
For example, when an application receives student information
as JSON text, it can use JSON.parse() to convert
that text into an object. The application can then access
individual properties such as the student's name and marks.
Example
const jsonText = '{"name":"Samadhan","marks":85}';
const student = JSON.parse(jsonText);
console.log(student.name);
console.log(student.marks);
Output
Samadhan
85
Explanation:
The jsonText variable stores JSON text as a string.
The JSON.parse() method converts it into a
JavaScript object stored in student. We can then
access its properties using dot notation.
2. Why Do We Use JSON.parse()?
Applications frequently receive or read data in JSON format. Because JSON data is text, it often needs to be parsed before the application can work with its values as JavaScript objects or arrays.
- API Responses: Convert JSON response text into JavaScript values when parsing is required.
- File Data: Read JSON text from a file and parse it into a usable value.
- Object Access: Access properties such as name, age, and marks after parsing.
- Array Processing: Convert JSON array text into a JavaScript array.
- Structured Data: Work with nested objects and arrays represented in JSON.
3. How JSON.parse() Works
The method takes a string containing valid JSON text. It parses the text and returns the JavaScript value represented by that JSON.
Step 1: JSON String
'{"name":"Samadhan","marks":85}'
Step 2: JSON.parse()
Reads and parses the JSON text.
Step 3: JavaScript Object
{ name: "Samadhan", marks: 85 }
Step 4: Access Values
Read properties such as student.name
and student.marks.
4. Syntax of JSON.parse()
The basic syntax accepts a JSON string. An optional reviver function can be supplied to transform values while parsing.
JSON.parse(text);
JSON.parse(text, reviver);
Parameters:
-
text: A string containing valid JSON text. -
reviver: An optional function that can transform parsed values before the final result is returned.
Return value: The method returns the JavaScript value represented by the JSON text. Depending on the input, this may be an object, array, string, number, boolean, or null.
JSON.parse() throws a SyntaxError.
5. Parse a Simple JSON Object
Let us convert JSON text containing student details into a JavaScript object and display its individual properties.
Program
const jsonText = `{
"name": "Pradnya",
"age": 22,
"city": "Pune"
}`;
const student = JSON.parse(jsonText);
console.log("Name:", student.name);
console.log("Age:", student.age);
console.log("City:", student.city);
Output
Name: Pradnya
Age: 22
City: Pune
Explanation:
-
jsonTextcontains a string written in JSON format. -
JSON.parse(jsonText)creates a JavaScript object. -
student.nameretrieves the name property. - The other properties are accessed in the same way.
6. Parse a JSON Array
JSON.parse() can convert JSON array text into a JavaScript array. After parsing, we can access array elements using their index positions.
Program
const jsonText = '["JavaScript","Node.js","SQL"]';
const skills = JSON.parse(jsonText);
console.log(skills);
console.log("First Skill:", skills[0]);
console.log("Second Skill:", skills[1]);
console.log("Total Skills:", skills.length);
Output
[ 'JavaScript', 'Node.js', 'SQL' ]
First Skill: JavaScript
Second Skill: Node.js
Total Skills: 3
Explanation:
The JSON string is converted into an array. The first element
is accessed using index 0, the second using
index 1, and length returns the
number of elements.
7. Parse Nested JSON Objects
JSON text can contain nested objects and arrays. After parsing, we can access their values using dot notation and array indexes.
Program
const jsonText = `{
"name": "Samadhan",
"course": "Node.js",
"address": {
"city": "Pune",
"state": "Maharashtra"
},
"skills": ["JavaScript", "Node.js"]
}`;
const student = JSON.parse(jsonText);
console.log("Name:", student.name);
console.log("City:", student.address.city);
console.log("State:", student.address.state);
console.log("First Skill:", student.skills[0]);
Output
Name: Samadhan
City: Pune
State: Maharashtra
First Skill: JavaScript
Explanation:
The address property contains a nested object.
Therefore, student.address.city accesses the city.
The skills property is an array, so its first
element is accessed with student.skills[0].
8. Parse Different JSON Data Types
JSON.parse() can return different JavaScript value types, depending on the JSON text supplied to it.
Program
console.log(JSON.parse('"Node.js"'));
console.log(JSON.parse('100'));
console.log(JSON.parse('true'));
console.log(JSON.parse('[10, 20, 30]'));
console.log(JSON.parse('null'));
Output
Node.js
100
true
[ 10, 20, 30 ]
null
Explanation: The first input is JSON text representing a string. The second represents a number, the third a boolean, the fourth an array, and the fifth the null value.
9. JSON.parse() vs JSON.stringify()
These two methods perform opposite conversion tasks. Understanding the difference helps prevent common mistakes.
JavaScript Object
{ name: "Samadhan", marks: 85 }
JSON.stringify()
Converts a JavaScript value into JSON text.
JSON String
{"name":"Samadhan","marks":85}
JSON.parse()
Parses JSON text back into a JavaScript value.
| JSON.stringify() | JSON.parse() |
|---|---|
| Converts a JavaScript value into JSON text. | Converts JSON text into a JavaScript value. |
| Input: JavaScript value. | Input: JSON string. |
| Output: JSON string for supported values. | Output: Parsed JavaScript value. |
10. Handle Invalid JSON Using try...catch
If the input string does not follow JSON syntax, JSON.parse()
throws a SyntaxError. A try...catch
block allows the application to handle that error without
terminating the normal flow unexpectedly.
Program
const jsonText = '{"name":"Samadhan", "age":22,}';
try {
const student = JSON.parse(jsonText);
console.log("JSON parsed successfully");
console.log(student);
} catch (error) {
console.log("Invalid JSON format");
}
Output
Invalid JSON format
Explanation:
The JSON text contains a trailing comma after the last property.
Standard JSON does not allow this syntax. Parsing fails, so
execution moves to the catch block.
11. Use the Reviver Function
JSON.parse() supports an optional reviver function. This function is called for parsed values and can transform selected values before the final result is returned.
Program
const jsonText = `{
"name": "Samadhan",
"marks": 85,
"bonus": 5
}`;
const student = JSON.parse(jsonText, function (key, value) {
if (key === "marks") {
return value + 5;
}
return value;
});
console.log(student.name);
console.log(student.marks);
console.log(student.bonus);
Output
Samadhan
90
5
Explanation:
When the reviver processes the marks property,
it adds 5 to the original value of 85. The final object
contains 90 for marks, while the other values remain unchanged.
The reviver should return the desired replacement value.
Returning undefined removes the corresponding
property from the resulting object or removes the element
from the resulting array.
12. Practical Program: Student Result Report
Let us parse student JSON text and generate a result report using the values stored in the resulting JavaScript object.
Complete Program
const jsonText = `{
"id": 101,
"name": "Samadhan",
"course": "Node.js",
"marks": 85,
"isPassed": true
}`;
try {
const student = JSON.parse(jsonText);
console.log("Student Result Report");
console.log("---------------------");
console.log("ID:", student.id);
console.log("Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);
console.log("Passed:", student.isPassed);
} catch (error) {
console.log("Unable to read student data");
}
Output
Student Result Report
---------------------
ID: 101
Name: Samadhan
Course: Node.js
Marks: 85
Passed: true
Detailed Explanation:
-
The
jsonTextvariable stores student details in valid JSON format. -
JSON.parse()converts the JSON string into a JavaScript object. - The program accesses the student's ID, name, course, marks, and pass status.
-
The
catchblock handles invalid JSON input.
13. How to Run the Program
-
Create a folder named
ParseExample. -
Create a JavaScript file named
app.js. - Paste the student result report program into the file.
- Open a terminal in that folder.
- Run the file using Node.js.
Terminal Command
node app.js
Node.js executes the JavaScript file and displays the parsed student information in the terminal.
14. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Passing a JavaScript object directly to JSON.parse(). | Pass a string containing valid JSON text. |
| Using single quotes inside JSON text. | JSON string values must use double quotes. |
| Leaving a trailing comma in JSON. | Remove the comma after the final property or array element. |
| Forgetting to handle parsing errors. | Use try...catch when input may be invalid. |
| Using JSON.stringify() to parse JSON text. | Use JSON.parse() for parsing and JSON.stringify() for serialization. |
15. Practice Tasks
Task 1: Parse Employee Data
Create a JSON string containing employee ID, name, department, and salary. Parse it and display each property.
Task 2: Parse an Array of Products
Create a JSON string containing three product names. Parse the string and display the first and last products.
Task 3: Handle Invalid JSON
Create a JSON string with an invalid trailing comma. Use try...catch to display a suitable error message. Then correct the JSON and run the program again.
Important Points
- JSON.parse() converts valid JSON text into a JavaScript value.
- It can return objects, arrays, strings, numbers, booleans, or null.
- The input must follow valid JSON syntax.
- Invalid JSON text causes a SyntaxError.
- try...catch can handle parsing errors.
- Nested objects and arrays can be accessed after parsing.
- The optional reviver function can transform parsed values.
Summary
JSON.parse() is a built-in JavaScript method that converts valid JSON text into a JavaScript value. It can create objects and arrays from JSON strings and can also parse strings, numbers, booleans, and null. Parsed object properties can be accessed using dot notation, while array elements can be accessed using indexes. Invalid JSON text causes a SyntaxError, so try...catch is useful when handling uncertain input. The optional reviver function can transform values during parsing. JSON.parse() is commonly used when applications need to work with structured data received or stored in JSON format.