toJSON()
ES5+A method that can be defined on an object to customize its JSON serialization.
Syntax
object.toJSON()Return Value
The value to be serialized
Examples
const user = {
name: 'John',
password: 'secret',
toJSON() {
return { name: this.name };
}
};
console.log(JSON.stringify(user)); 📌 When to Use
Define toJSON() on custom classes to control their JSON representation, hide private data, or serialize complex objects into a simpler format.
⚠️ Common Mistakes
Defining toJSON() that returns the object itself, causing infinite recursion.
Forgetting that toJSON() return value is also stringified, so return objects, not strings.
✅ Best Practices
Use toJSON() to exclude computed properties, methods, and circular references from serialization.
Return a plain object with only the data you want serialized.
⚡ Performance Notes
toJSON() is called once per object during stringify. Keep it simple to avoid performance issues with large object graphs.
🌍 Real World Example
Custom User Class Serialization
Define a User class that controls which properties are serialized to JSON.
class User {
constructor(id, name, email, password) {
this.id = id;
this.name = name;
this.email = email;
this._password = password; // Private
this._createdAt = new Date();
}
get isAdmin() {
return this.email.endsWith('@admin.com');
}
toJSON() {
return {
id: this.id,
name: this.name,
email: this.email,
isAdmin: this.isAdmin,
createdAt: this._createdAt.toISOString()
// password is excluded!
};
}
}
const user = new User(1, 'John', 'john@admin.com', 'secret123');
console.log(JSON.stringify(user, null, 2));
// { "id": 1, "name": "John", "email": "john@admin.com", "isAdmin": true, "createdAt": "2024-..." }