Custom toJSON()
Define a toJSON() method on an object to control how it serializes to JSON. JSON.stringify calls this method automatically if present.
Define a toJSON() method on an object to control how it serializes to JSON. JSON.stringify calls this method automatically if present.
class User {
constructor(name, password) {
this.name = name;
this.password = password;
}
toJSON() {
// Return only safe properties
return { name: this.name };
}
}
const user = new User("Alice", "secret");
JSON.stringify(user);
// {"name":"Alice"} — password excluded
// Date has a built-in toJSON()
new Date().toJSON(); // "2024-06-15T10:30:00.000Z"
Implement toJSON() on classes to control serialization — never accidentally expose sensitive fields in API responses.
More in JavaScript