-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In the previous tutorial, we learned how to parse JSON strings into JavaScript objects using JSON.parse()
.
Now, it’s time to learn the opposite process: converting JavaScript objects into JSON strings. This is done using JSON.stringify()
.
JSON.stringify()
is essential when you want to send data from your web application to a server or save it in local storage.
JSON.stringify()
is a built-in JavaScript method that converts a JavaScript object or array into a JSON string.
Input: JavaScript object or array
Output: JSON string (text format)
Once converted, this string can be sent over the network or stored in files.
let user = {
name: "Vicky",
age: 28,
isDeveloper: true
};
let jsonString = JSON.stringify(user);
console.log(jsonString);
Output:
{"name":"Vicky","age":28,"isDeveloper":true}
Explanation:
user
is a JavaScript object.
JSON.stringify(user)
converts it into a JSON string.
You can now send jsonString
to a server or save it in local storage.
When sending data via APIs, browsers, or servers, data must be in text format.
JavaScript objects cannot be sent directly — they need to be stringified first.
Example with fetch()
:
let user = { name: "Vicky", age: 28 };
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user) // Convert object to JSON string
})
.then(response => response.json())
.then(data => console.log(data));
Without JSON.stringify()
, body: user
would fail because the server expects a string, not an object.
You can also convert arrays into JSON strings.
let skills = ["HTML", "CSS", "JavaScript"];
let jsonSkills = JSON.stringify(skills);
console.log(jsonSkills);
Output:
["HTML","CSS","JavaScript"]
After stringifying, this array can be sent to a server or stored just like an object.
JSON.stringify()
works for nested objects as well.
let user = {
name: "Vicky",
age: 28,
address: {
city: "Mumbai",
zipcode: 400001
}
};
let jsonString = JSON.stringify(user);
console.log(jsonString);
Output:
{"name":"Vicky","age":28,"address":{"city":"Mumbai","zipcode":400001}}
Nested objects are fully converted into a string, preserving structure.
JSON.stringify()
allows optional parameters to format the output for readability.
Syntax:
JSON.stringify(value, replacer, space)
value
: The object or array to convert
replacer
: Optional; a function or array to filter keys
space
: Optional; number of spaces for indentation
Example:
let user = { name: "Vicky", age: 28, skills: ["HTML","CSS","JS"] };
let formattedJSON = JSON.stringify(user, null, 2);
console.log(formattedJSON);
Output:
{
"name": "Vicky",
"age": 28,
"skills": [
"HTML",
"CSS",
"JS"
]
}
This makes the JSON easy to read and debug.
A replacer allows you to control which keys are included in the string.
let user = { name: "Vicky", age: 28, password: "secret" };
let jsonString = JSON.stringify(user, (key, value) => {
if (key === "password") return undefined; // Exclude password
return value;
});
console.log(jsonString);
Output:
{"name":"Vicky","age":28}
The password
key is excluded from the string. This is useful for security purposes.
Local storage can only store strings. So if you want to save an object:
let user = { name: "Vicky", age: 28, skills: ["HTML","CSS","JS"] };
// Convert to JSON string
localStorage.setItem("userData", JSON.stringify(user));
// Retrieve and parse later
let storedUser = JSON.parse(localStorage.getItem("userData"));
console.log(storedUser.name); // Output: Vicky
This demonstrates how JSON.stringify()
and JSON.parse()
work together in real-world applications.
Functions are ignored
let obj = { name: "Vicky", greet: () => "Hello" };
console.log(JSON.stringify(obj)); // Output: {"name":"Vicky"}
Undefined values are ignored
let obj = { name: "Vicky", age: undefined };
console.log(JSON.stringify(obj)); // Output: {"name":"Vicky"}
Symbols are ignored
let obj = { id: Symbol("id") };
console.log(JSON.stringify(obj)); // Output: {}
Use replacer and space parameters for filtering and pretty printing.
JSON.stringify()
converts JavaScript objects or arrays into JSON strings.
Necessary when sending data to servers or storing in text-based storage.
Supports optional replacer and space parameters for filtering and formatting.
Functions, undefined values, and symbols are ignored during stringification.
Works with arrays, nested objects, and complex structures.
Mastering JSON.stringify()
allows you to efficiently send and store data in web applications, completing the core skills for working with JSON in JavaScript.
Convert the following JavaScript object into a JSON string using JSON.stringify()
:
let user = { name: "Vicky", age: 28, isDeveloper: true };
Stringify the following array of numbers and print the resulting JSON string:
let scores = [88, 95, 72, 100];
Convert this nested object into a JSON string and ensure it is formatted with 2-space indentation:
let user = { name: "Sanjana", age: 26, address: { city: "Delhi", zipcode: 110001 } };
Given this object, exclude the password
property when converting to JSON:
let user = { username: "vicky123", password: "secret", email: "vicky@example.com" };
Create a JSON string from this array of objects representing books:
let books = [
{ title: "Learn JS", author: "Vicky" },
{ title: "Master PHP", author: "Sanjana" }
];
Convert a JavaScript object containing functions and undefined values into a JSON string. Observe what happens to these values:
let obj = { name: "Vicky", greet: () => "Hello", age: undefined };
Store the following JavaScript object in local storage as a JSON string:
let settings = { theme: "dark", fontSize: 16, notifications: true };
Stringify a JavaScript object and then parse it back using JSON.parse()
. Verify that you can access one of its properties. Example object:
let product = { id: 101, name: "Laptop", price: 55000 };
Convert this nested array into a JSON string and print the result:
let data = [["HTML", "CSS"], ["JavaScript", "React"]];
Use a replacer function to stringify the following object but exclude the salary
property:
let employee = { name: "Vicky", role: "Developer", salary: 50000 };
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts