The JSON.stringify()
method in JavaScript is used to convert a JavaScript object, array, or value into a JSON-formatted string. This is useful for sending data over a network, saving it in local storage, or logging structured data.
Syntax
JSON.stringify(value[, replacer[, space]]);
Parameters:
value
:- The JavaScript object or value to be converted to a JSON string.
replacer
(Optional):- A function or an array that controls how object values are stringified.
- If omitted, all properties of the object are included.
space
(Optional):- A number or string used to insert whitespace for readability in the output JSON string.
- Numbers specify indentation levels, and strings define indentation characters.
Examples
Basic Usage
Convert an object to a JSON string:
const user = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // Output: {"name":"Alice","age":25}
Pretty-Print JSON
Add indentation using the space
parameter:
const user = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(user, null, 4); // 4 spaces for indentation
console.log(jsonString);
/*
Output:
{
"name": "Alice",
"age": 25
}
*/
Using a replacer
Function
Control the output with a function:
const user = { name: "Alice", age: 25, password: "secret" };
const jsonString = JSON.stringify(user, (key, value) => {
if (key === "password") {
return undefined; // Exclude sensitive data
}
return value;
});
console.log(jsonString); // Output: {"name":"Alice","age":25}
Using a replacer
Array
Specify which properties to include:
const user = { name: "Alice", age: 25, password: "secret" };
const jsonString = JSON.stringify(user, ["name", "age"]);
console.log(jsonString); // Output: {"name":"Alice","age":25}
Error Handling
- Cyclic References:
- If an object contains circular references,
JSON.stringify()
will throw aTypeError
. - Example:
- If an object contains circular references,
const obj = {};
obj.self = obj; // Circular reference
JSON.stringify(obj); // Throws a TypeError
- Solution: Use libraries like CircularJSON.
- Unsupported Data Types:
- Functions,
undefined
, orSymbol
values are not serialized and will be omitted or replaced withnull
in arrays:
- Functions,
const obj = { func: () => {}, undef: undefined, symbol: Symbol("test") };
console.log(JSON.stringify(obj)); // Output: {}
Common Use Cases
- Saving Data in Local Storage:
const user = { name: "Bob", age: 30 };
localStorage.setItem("user", JSON.stringify(user));
- Sending Data to a Server:
const data = { name: "Alice", score: 100 };
fetch('/api/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
- Debugging: Format objects for easier reading in logs:
const data = { name: "Alice", age: 25 };
console.log(JSON.stringify(data, null, 2)); // Pretty-print for logs
Key Points
- Immutable Output: The resulting JSON string is immutable and cannot be modified.
- Use Case: Ideal for serializing structured data for storage, transmission, or logging.
- Custom Output: Tailor output with
replacer
andspace
options.
For more insights and JavaScript tutorials, visit The Coding College.