JSON.stringify()
15 April 2025 | Category: JavaScript
The JSON.stringify()
method is used to convert a JavaScript object or array into a JSON-formatted string.
âś… In simple words:
JavaScript object → JSON string
📦 Syntax
JSON.stringify(value[, replacer[, space]]);
Parameters:
value
: The JavaScript value you want to convert.replacer
(optional): A function or array to filter properties.space
(optional): A number or string for pretty-printing (indentation).
âś… Example 1: Convert Object to JSON String
const user = {
name: "Alice",
age: 25,
isStudent: false
};
const jsonStr = JSON.stringify(user);
console.log(jsonStr);
// Output: {"name":"Alice","age":25,"isStudent":false}
âś… Example 2: Convert Array to JSON String
const fruits = ["apple", "banana", "mango"];
const jsonFruits = JSON.stringify(fruits);
console.log(jsonFruits);
// Output: ["apple","banana","mango"]
🎨 Example 3: Pretty Print with Indentation
const user = { name: "Bob", age: 30 };
const formattedJson = JSON.stringify(user, null, 2);
console.log(formattedJson);
/*
Output:
{
"name": "Bob",
"age": 30
}
*/
đź§ Optional: Using replacer
to Filter Properties
You can control which properties to include:
🔹 Using an array:
const person = { name: "Alice", age: 25, city: "Delhi" };
const filtered = JSON.stringify(person, ["name", "city"]);
console.log(filtered);
// Output: {"name":"Alice","city":"Delhi"}
🔹 Using a function:
const person = { name: "Alice", age: 25, city: "Delhi" };
const custom = JSON.stringify(person, (key, value) => {
if (typeof value === "number") return undefined;
return value;
});
console.log(custom);
// Output: {"name":"Alice","city":"Delhi"}
⚠️ Important Notes
JSON.stringify()
doesn’t includeundefined
, functions, or symbols.- Circular references (objects referring to themselves) will cause an error.
âś… Summary
Feature | Description |
---|---|
Converts | JavaScript value → JSON string |
Used in | APIs, localStorage, data saving |
Optional Parameters | replacer , space for customization |
Pretty Printing | Use space parameter for readable output |