SyntaxStudy
Sign Up
JavaScript Custom toJSON() Method
JavaScript Intermediate 4 min read

Custom toJSON() Method

Custom toJSON()

Define a toJSON() method on an object to control how it serializes to JSON. JSON.stringify calls this method automatically if present.

Example
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"
Pro Tip

Implement toJSON() on classes to control serialization — never accidentally expose sensitive fields in API responses.