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
const student = {
name: "Samadhan",
course: "Node.js",
marks: 85
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
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.
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.
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
const student = {
name: "Pradnya",
age: 22,
city: "Pune"
};
const result = JSON.stringify(student);
console.log(result);
console.log(typeof result);
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
const skills = [
"JavaScript",
"Node.js",
"SQL"
];
const jsonSkills = JSON.stringify(skills);
console.log(jsonSkills);
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
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
{"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
const student = {
name: "Samadhan",
course: "Node.js",
marks: 85
};
const jsonData = JSON.stringify(student, null, 4);
console.log(jsonData);
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
{"name":"Samadhan","marks":85}
Uses fewer whitespace characters and is compact.
Formatted JSON
{
"name": "Samadhan",
"marks": 85
}
Uses indentation and line breaks to improve readability.
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
const student = {
name: "Samadhan",
course: "Node.js",
marks: 85,
city: "Pune"
};
const jsonData = JSON.stringify(
student,
["name", "marks"],
4
);
console.log(jsonData);
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
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
"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
const student = {
name: "Samadhan",
nickname: undefined,
marks: 85
};
console.log(JSON.stringify(student));
Output
{"name":"Samadhan","marks":85}
The nickname property is omitted because its
value is undefined.
Example: Undefined Values in Arrays
const values = [10, undefined, 30];
console.log(JSON.stringify(values));
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
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
Student JSON Report:
{
"id": 101,
"name": "Samadhan",
"course": "Node.js",
"marks": 85,
"isPassed": true,
"skills": [
"JavaScript",
"Node.js",
"SQL"
]
}
Detailed Explanation:
-
The
studentobject 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
-
Create a folder named
StringifyExample. -
Create a JavaScript file named
app.js. - Paste the student JSON report program into the file.
- Open a terminal in the project folder.
- Execute the program using Node.js.
Terminal Command
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.