JSON.stringify()
The JSON.stringify()
static method in JavaScript is used to convert a JavaScript object or value into a JSON string. It can optionally include a replacer function or array and control formatting with a space parameter.
Syntax
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
Parameters
Parameter | Description |
---|---|
value | The value to convert to a JSON string. It can be an object, array, string, number, or boolean. |
replacer (optional) | A function or array that alters the behavior of the stringification process. If omitted, all properties of the object are included. |
space (optional) | A string or number used for pretty-printing the JSON output. Numbers indicate the number of spaces; strings are directly used for indentation. |
Return Value
The JSON.stringify()
method returns a string representing the JSON-formatted version of the given value.
Examples
1. Converting an Object to JSON
In this example, an object is converted to a JSON string using JSON.stringify()
.
const user = { name: "Arjun", age: 25, city: "New York" };
const jsonString = JSON.stringify(user);
console.log(jsonString);
Output
{"name":"Arjun","age":25,"city":"New York"}
- The
JSON.stringify()
method converts theuser
object to a JSON string.
2. Using a Replacer Function
The replacer function can be used to filter or transform properties during stringification.
const user = { name: "Arjun", age: 25, city: "New York" };
const jsonString = JSON.stringify(user, (key, value) => {
if (key === "age") {
return undefined; // Exclude the "age" property
}
return value;
});
console.log(jsonString);
Output
{"name":"Arjun","city":"New York"}
- The replacer function excludes the
age
property from the final JSON string.
3. Using an Array as Replacer
An array replacer allows you to specify which properties should be included in the JSON string.
const user = { name: "Arjun", age: 25, city: "New York" };
const jsonString = JSON.stringify(user, ["name", "city"]);
console.log(jsonString);
Output
{"name":"Arjun","city":"New York"}
- Only the
name
andcity
properties are included in the JSON string.
4. Pretty-Printing JSON
The space
parameter is used to format the JSON output with indentation for better readability.
const user = { name: "Arjun", age: 25, city: "New York" };
const jsonString = JSON.stringify(user, null, 2);
console.log(jsonString);
Output
{
"name": "Arjun",
"age": 25,
"city": "New York"
}
- The
space
parameter formats the JSON string with a 2-space indentation.
5. Handling Circular References
Using JSON.stringify()
with circular references will throw an error. You can handle this with a replacer function.
const obj = {};
obj.self = obj;
const jsonString = JSON.stringify(obj, (key, value) => {
if (value === obj) {
return "[Circular]";
}
return value;
});
console.log(jsonString);
Output
"[Circular]"
- The replacer function detects circular references and replaces them with a placeholder.