Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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

JavaScript
const jsonText = '{"name":"Samadhan","marks":85}';

const student = JSON.parse(jsonText);

console.log(student.name);
console.log(student.marks);

Output

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.

Definition: JSON.parse() converts valid JSON text into a JavaScript value.

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.

Syntax
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.

Important: The input must be valid JSON text. If the text is invalid, 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

JavaScript - app.js
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

Output
Name: Pradnya
Age: 22
City: Pune

Explanation:

  • jsonText contains a string written in JSON format.
  • JSON.parse(jsonText) creates a JavaScript object.
  • student.name retrieves 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

JavaScript
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

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

JavaScript
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

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

JavaScript
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

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

JavaScript - app.js
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

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.

Best Practice: When JSON text comes from an external source or user input, handle parsing errors appropriately.

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

JavaScript
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

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

JavaScript - app.js
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

Output
Student Result Report
---------------------
ID: 101
Name: Samadhan
Course: Node.js
Marks: 85
Passed: true

Detailed Explanation:

  • The jsonText variable 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 catch block handles invalid JSON input.

13. How to Run the Program

  1. Create a folder named ParseExample.
  2. Create a JavaScript file named app.js.
  3. Paste the student result report program into the file.
  4. Open a terminal in that folder.
  5. Run the file using Node.js.

Terminal Command

Terminal
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.