JSON.stringify() in JavaScript
Master JSON.stringify() in JavaScript: syntax, replacer functions, indentation, handling of special values like undefined, dates, and circular references.
Detailed Explanation
JSON.stringify() is the built-in JavaScript method for converting a JavaScript value into a JSON-formatted string. It is one of the most frequently used methods in web development, essential for sending data to APIs, storing data in localStorage, and serializing objects for logging.
Method signature:
JSON.stringify(value, replacer?, space?)
- value: The JavaScript value to serialize (object, array, primitive)
- replacer: Optional function or array that filters/transforms properties
- space: Optional number (1-10) or string for indentation
Basic usage:
JSON.stringify({ name: "Alice", age: 30 })
// '{"name":"Alice","age":30}'
JSON.stringify({ name: "Alice" }, null, 2)
// '{\n "name": "Alice"\n}'
The replacer parameter:
A replacer function receives each key-value pair and can transform the value:
JSON.stringify(data, (key, value) => {
if (typeof value === 'string') return value.toUpperCase();
return value;
});
An array replacer acts as a whitelist, including only specified keys:
JSON.stringify(user, ['name', 'email']); // only these keys
Values that are silently dropped or transformed:
undefined, functions, and Symbols are omitted from objects- In arrays, they become
null:[1, undefined, 3]->[1,null,3] Dateobjects are serialized via their.toISOString()methodNaNandInfinitybecomenullBigIntthrows aTypeError(you must convert it yourself)- Circular references throw a
TypeError
The toJSON() method:
If an object has a toJSON() method, JSON.stringify() calls it and serializes the return value instead of the object itself. This is how Date objects produce ISO strings. You can define toJSON() on your own classes to control serialization:
class User {
constructor(name, passwordHash) {
this.name = name;
this.passwordHash = passwordHash;
}
toJSON() {
return { name: this.name }; // exclude sensitive data
}
}
Common mistakes developers make:
The most critical mistake is assuming JSON.stringify() preserves all data. Properties with undefined values silently disappear, which can cause subtle bugs when round-tripping data through JSON. Another mistake is forgetting to handle circular references, which crash with an unhelpful TypeError. Use a library like flatted or write a custom replacer to handle cycles. Developers also sometimes stringify an already-stringified value, producing double-encoded JSON ("\"{\\\"key\\\":\\\"value\\\"}\").
Best practices:
Always consider what data types are in your object before stringifying. Use a replacer to exclude sensitive fields like passwords or tokens. When storing data that must survive round-tripping, test that JSON.parse(JSON.stringify(data)) produces the expected result. Handle errors from BigInt and circular references explicitly.
Use Case
Serializing a JavaScript object to send as the body of a fetch() POST request with Content-Type: application/json, while filtering out sensitive fields using a replacer function.