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.stringify() in Node.js

Learn how JSON.stringify() converts JavaScript values into JSON-formatted strings. Understand its syntax, working, practical examples, nested objects, arrays, formatting options, and common mistakes through detailed programs and outputs.

1. What Is JSON.stringify()?

JSON.stringify() is a built-in JavaScript method used to convert a JavaScript value into a JSON-formatted string. It is useful when data needs to be transmitted between applications or stored as text.

For example, a JavaScript object can contain a student's name, course, and marks. If we want to represent this object as JSON text, we can use JSON.stringify().

Example

JavaScript
const student = {
    name: "Samadhan",
    course: "Node.js",
    marks: 85
};

const jsonData = JSON.stringify(student);

console.log(jsonData);

Output

Output
{"name":"Samadhan","course":"Node.js","marks":85}

Explanation: The student variable contains a JavaScript object. The JSON.stringify(student) method converts that object into a JSON string, which is stored in jsonData.

Definition: JSON.stringify() converts a JavaScript value into a JSON-formatted string.

2. Why Do We Use JSON.stringify()?

JavaScript applications frequently work with objects and arrays. When data needs to be represented as JSON text, the JSON.stringify() method provides a convenient way to convert those values.

  • Data Exchange: Convert objects into JSON text before sending data to another application.
  • API Communication: Prepare JSON request data when communicating with APIs.
  • Text Storage: Convert structured data into text before writing it to a file.
  • Readable Output: Represent objects and arrays as JSON text.
  • Data Conversion: Convert supported JavaScript values into their JSON representation.

3. How JSON.stringify() Works

The method takes a JavaScript value and produces a JSON string representing that value. The resulting string can then be displayed, transmitted, or stored.

Step 1: JavaScript Object

{ name: "Samadhan", marks: 85 }

↓
Step 2: JSON.stringify()

Converts the JavaScript object into JSON text.

↓
Step 3: JSON String

{"name":"Samadhan","marks":85}

↓
Step 4: Use the String

Display it, transmit it, or save it as text.

4. Syntax of JSON.stringify()

The basic syntax accepts a JavaScript value. It also supports optional arguments for selecting properties and formatting the resulting JSON string.

Syntax
JSON.stringify(value);
JSON.stringify(value, replacer);
JSON.stringify(value, replacer, space);

Parameters:

  • value: The JavaScript value to convert.
  • replacer: An optional function or array used to control which values or properties are included.
  • space: An optional number or string used to format the output with indentation.

The method returns a JSON string for values that can be represented in JSON. Some values, such as a top-level undefined or function, produce undefined rather than a JSON string.

5. Convert a Simple JavaScript Object

Let us create a student object and convert it into JSON text.

Program

JavaScript - app.js
const student = {
    name: "Pradnya",
    age: 22,
    city: "Pune"
};

const result = JSON.stringify(student);

console.log(result);
console.log(typeof result);

Output

Output
{"name":"Pradnya","age":22,"city":"Pune"}
string

Explanation: The first output shows the JSON representation of the object. The typeof operator returns "string" because JSON.stringify() produces text.

6. Convert a JavaScript Array

JSON.stringify() can also convert an array into a JSON string. Array elements are preserved in their original order.

Program

JavaScript
const skills = [
    "JavaScript",
    "Node.js",
    "SQL"
];

const jsonSkills = JSON.stringify(skills);

console.log(jsonSkills);

Output

Output
["JavaScript","Node.js","SQL"]

Explanation: The array is converted into a JSON string containing the same three string values in the same order.

7. Convert Nested Objects

JavaScript objects can contain other objects and arrays. JSON.stringify() can convert these nested structures into a JSON string.

Program

JavaScript
const student = {
    name: "Samadhan",
    course: "Node.js",
    address: {
        city: "Pune",
        state: "Maharashtra"
    },
    skills: ["JavaScript", "Node.js"]
};

const jsonData = JSON.stringify(student);

console.log(jsonData);

Output

Output
{"name":"Samadhan","course":"Node.js","address":{"city":"Pune","state":"Maharashtra"},"skills":["JavaScript","Node.js"]}

Explanation: The output contains the nested address object and skills array. JSON.stringify() converts the entire supported structure into one JSON string.

8. Format JSON Using the Space Parameter

By default, JSON.stringify() creates compact JSON text. To make the result easier to read, we can provide the optional third parameter, space.

When space is a number, it specifies the number of indentation spaces, up to a maximum of 10.

Program

JavaScript
const student = {
    name: "Samadhan",
    course: "Node.js",
    marks: 85
};

const jsonData = JSON.stringify(student, null, 4);

console.log(jsonData);

Output

Output
{
    "name": "Samadhan",
    "course": "Node.js",
    "marks": 85
}

Explanation: The second argument is null, meaning no replacer is used. The third argument, 4, formats the result with four spaces of indentation at each nesting level.

9. Compact JSON vs Formatted JSON

Both examples represent the same data. The difference is only in how the JSON string is formatted.

Compact JSON
Output
{"name":"Samadhan","marks":85}

Uses fewer whitespace characters and is compact.

Formatted JSON
Output
{
    "name": "Samadhan",
    "marks": 85
}

Uses indentation and line breaks to improve readability.

Remember: Formatting changes the appearance of the JSON string, not the underlying data represented by it.

10. Use a Replacer Array

The second parameter of JSON.stringify() can be an array of property names. When serializing an object, this array specifies which properties should be included.

Program

JavaScript
const student = {
    name: "Samadhan",
    course: "Node.js",
    marks: 85,
    city: "Pune"
};

const jsonData = JSON.stringify(
    student,
    ["name", "marks"],
    4
);

console.log(jsonData);

Output

Output
{
    "name": "Samadhan",
    "marks": 85
}

Explanation: The replacer array contains only "name" and "marks". Therefore, those properties are included in the output, while course and city are omitted from the serialized object.

11. Convert Data Types into JSON Strings

JSON.stringify() can serialize many JavaScript values, including strings, numbers, booleans, arrays, and objects.

Program

JavaScript
console.log(JSON.stringify("Node.js"));
console.log(JSON.stringify(100));
console.log(JSON.stringify(true));
console.log(JSON.stringify([10, 20, 30]));
console.log(JSON.stringify({ city: "Pune" }));

Output

Output
"Node.js"
100
true
[10,20,30]
{"city":"Pune"}

Explanation: Each supported value is converted into its JSON representation. Notice that a string appears with double quotes in the JSON text.

12. Important Behaviour of JSON.stringify()

JSON.stringify() does not serialize every JavaScript value exactly as it exists in memory. Some values are omitted or represented differently according to JSON serialization rules.

Example: Undefined Values in Objects

JavaScript
const student = {
    name: "Samadhan",
    nickname: undefined,
    marks: 85
};

console.log(JSON.stringify(student));

Output

Output
{"name":"Samadhan","marks":85}

The nickname property is omitted because its value is undefined.

Example: Undefined Values in Arrays

JavaScript
const values = [10, undefined, 30];

console.log(JSON.stringify(values));

Output

Output
[10,null,30]

In an array, an undefined element is represented as null in the serialized JSON string.

13. Practical Program: Student JSON Report

Let us create a complete student object, convert it into formatted JSON text, and display the result.

Complete Program

JavaScript - app.js
const student = {
    id: 101,
    name: "Samadhan",
    course: "Node.js",
    marks: 85,
    isPassed: true,
    skills: ["JavaScript", "Node.js", "SQL"]
};

const jsonData = JSON.stringify(student, null, 4);

console.log("Student JSON Report:");
console.log(jsonData);

Output

Output
Student JSON Report:
{
    "id": 101,
    "name": "Samadhan",
    "course": "Node.js",
    "marks": 85,
    "isPassed": true,
    "skills": [
        "JavaScript",
        "Node.js",
        "SQL"
    ]
}

Detailed Explanation:

  • The student object contains numeric, string, boolean, and array values.
  • JSON.stringify(student, null, 4) converts the object into JSON text and formats it with indentation.
  • console.log() displays the heading and the resulting JSON string in the terminal.

14. How to Run the Program

  1. Create a folder named StringifyExample.
  2. Create a JavaScript file named app.js.
  3. Paste the student JSON report program into the file.
  4. Open a terminal in the project folder.
  5. Execute the program using Node.js.

Terminal Command

Terminal
node app.js

Node.js executes the JavaScript file and prints the formatted JSON report in the terminal.

15. Common Mistakes

Mistake Correct Approach
Expecting JSON.stringify() to return an object. It returns a JSON string for supported values.
Using JSON.stringify() when parsing JSON text. Use JSON.parse() to parse JSON text.
Expecting undefined object properties to appear. Undefined-valued object properties are omitted.
Expecting compact JSON to include indentation. Pass a space argument to format the output.
Assuming every JavaScript value can be serialized. Some values have special serialization behaviour.
Expecting a replacer array to include every property. Include the desired property names in the replacer array.

16. Practice Tasks

Task 1: Convert Employee Data

Create an employee object containing ID, name, department, and salary. Convert it into a JSON string and display it.

Task 2: Format Product JSON

Create a product object containing product name, price, category, and availability. Use JSON.stringify() with four spaces of indentation.

Task 3: Select Specific Properties

Create a student object containing name, course, marks, and city. Use a replacer array to include only name and marks.

Important Points

  • JSON.stringify() converts supported JavaScript values into JSON-formatted strings.
  • It supports objects, arrays, strings, numbers, booleans, and null.
  • The space parameter controls indentation in the output.
  • A replacer array can select properties to include when serializing objects.
  • Undefined-valued object properties are omitted.
  • Undefined array elements are serialized as null.
  • JSON.stringify() creates JSON text; it does not parse JSON text into an object.
  • Use JSON.parse() when you need to parse valid JSON text.

Summary

JSON.stringify() is a built-in JavaScript method that converts supported JavaScript values into JSON-formatted strings. It can serialize objects, arrays, strings, numbers, booleans, and null. The optional replacer parameter can control which properties are included, while the space parameter formats the output with indentation. Undefined object properties are omitted, and undefined array elements are represented as null. JSON.stringify() is useful for preparing structured data for transmission, display, and text storage. Use JSON.parse() when JSON text needs to be converted back into a JavaScript value.