ToJSON Method
You'll learn how to customize an object's JSON serialization by implementing a toJSON method.
What is the toJSON Method?
When you call JSON.stringify() on an object, JavaScript first checks if that object has a method named toJSON. If it exists, JavaScript calls it and serializes whatever that method returns instead of the object itself.
Think of toJSON as a "translation service" for your object. Just like a professional translator decides how to best express ideas in another language, toJSON decides how your object should be expressed as JSON.
How It Works
When JSON.stringify encounters an object with a toJSON method:
- It calls
obj.toJSON() - It serializes the returned value instead of the original object
const user = {
name: "Alice",
password: "secret123",
created: new Date(),
toJSON() {
return {
name: this.name,
created: this.created
};
}
};
JSON.stringify(user);
// '{"name":"Alice","created":"2024-..."}'
// Password is excluded!
Common Use Cases
Hiding sensitive data:
const account = {
id: 42,
balance: 1000,
ssn: "123-45-6789",
toJSON() {
return { id: this.id, balance: this.balance };
}
};
Custom formatting:
const range = {
min: 10,
max: 50,
toJSON() {
return `${this.min}-${this.max}`;
}
};
Key Takeaway: Implementing a toJSON method lets you control exactly what gets serialized when JSON.stringify is called, perfect for hiding sensitive data or creating custom representations.