-
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
When working with modern web applications, data constantly moves between the browser, server, storage, and APIs. JavaScript objects are easy to work with inside the code, but they cannot be sent or stored directly in many situations. This is where JSON.stringify() becomes essential. It converts JavaScript values into JSON formatted strings that can be stored, transmitted, or logged safely.
In this tutorial, you will learn what JSON.stringify() is, why it is important, how it works, its syntax, detailed examples, common mistakes, best practices, and real world use cases.
JSON.stringify() is a JavaScript method that converts a JavaScript object, array, or value into a JSON string. This JSON string can then be sent to a server, saved in browser storage, or used for data exchange between systems.
In simple terms, JSON.stringify() turns JavaScript data into text that follows JSON rules.
JSON.stringify() is important because it allows developers to:
Send data to servers using AJAX or Fetch
Store structured data in localStorage or sessionStorage
Save application state
Convert objects into readable text
Exchange data between frontend and backend
Work efficiently with APIs
Without this method, JavaScript objects would not be compatible with many storage and communication mechanisms.
JSON.stringify(value, replacer, space)
value is the data to convert into JSON
replacer is optional and controls which properties are included
space is optional and adds formatting for readability
The method returns a JSON formatted string.
let user = {
name: "Amit",
age: 27
};
let jsonText = JSON.stringify(user);
console.log(jsonText);
Output:
{"name":"Amit","age":27}
The object is now converted into a string.
let cities = ["Delhi", "Mumbai", "Bengaluru"];
let jsonCities = JSON.stringify(cities);
console.log(jsonCities);
Arrays are converted correctly into JSON array strings.
let employee = {
name: "Neha",
department: "IT",
address: {
city: "Pune",
state: "Maharashtra"
}
};
let data = JSON.stringify(employee);
console.log(data);
Nested objects remain structured in JSON format.
let info = {
active: true,
score: 92
};
let result = JSON.stringify(info);
console.log(result);
Primitive values are converted without issues.
Browser storage accepts only strings. JSON.stringify() is required to store objects.
let profile = {
name: "Rahul",
role: "Designer"
};
localStorage.setItem("profile", JSON.stringify(profile));
Reading the data later requires JSON.parse().
let settings = {
theme: "dark",
language: "en"
};
sessionStorage.setItem("settings", JSON.stringify(settings));
This is commonly used for temporary user preferences.
When sending data to a server, objects must be stringified.
let data = {
name: "Suman",
email: "suman@gmail.com"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
This is a standard pattern in API communication.
fetch("submit.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
product: "Laptop",
price: 55000
})
});
Fetch makes heavy use of JSON.stringify().
The space parameter improves readability.
let user = {
name: "Kiran",
age: 24,
city: "Jaipur"
};
let formatted = JSON.stringify(user, null, 4);
console.log(formatted);
This is helpful for debugging and logging.
The replacer allows filtering properties.
let student = {
name: "Anjali",
marks: 85,
grade: "A"
};
let result = JSON.stringify(student, ["name", "grade"]);
console.log(result);
Only selected properties are included.
let data = {
name: "Vikas",
salary: 50000
};
let json = JSON.stringify(data, function (key, value) {
if (key === "salary") {
return undefined;
}
return value;
});
console.log(json);
This is useful for hiding sensitive data.
Some values are skipped automatically.
Functions
Undefined values
Symbols
let obj = {
name: "Ramesh",
greet: function () {}
};
console.log(JSON.stringify(obj));
The function is ignored.
Dates are converted to strings.
let event = {
date: new Date()
};
console.log(JSON.stringify(event));
Dates must be restored manually using JSON.parse() logic.
Trying to stringify circular references
Expecting functions to be included
Forgetting to parse stored JSON
Storing sensitive data in plain text
Overusing formatting in production
Avoiding these mistakes prevents errors and security risks.
Always validate data before stringifying
Avoid storing passwords or tokens
Use formatting only for debugging
Keep JSON payloads minimal
Combine with JSON.parse() properly
These practices ensure clean and secure applications.
toString() does not produce valid JSON.
JSON.stringify() creates standard JSON
toString() creates unreadable strings
JSON output is portable and structured
Always prefer JSON.stringify() for data exchange.
Large objects increase processing time
Avoid unnecessary stringify operations
Optimize object size
Cache results when possible
Efficient usage improves performance.
JSON.stringify() is widely used in:
API request payloads
Local and session storage
State management systems
Logging and debugging
Offline applications
Form data submission
It is a core method in modern JavaScript development.
JSON.stringify() is supported by all modern browsers and is safe to use in production environments.
The JSON.stringify() method is essential for converting JavaScript objects into JSON strings that can be stored, transmitted, or shared between systems. It plays a critical role in API communication, browser storage, and application state management. By understanding its syntax, optional parameters, common pitfalls, and best practices, you can use JSON.stringify() effectively to build reliable, secure, and high performance JavaScript applications.
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
