How to define a custom toJSON() method on an object to control how it is serialized in TypeScript

1 Answer

0 votes
class User {
  userid: number;
  username: string;
  age: number;
  private password: string; // should not be serialized

  constructor(userid: number, username: string, age: number, password: string) {
    this.userid = userid;
    this.username = username;
    this.age = age;
    this.password = password;
  }

  toJSON() {
    // Exclude sensitive data like password
    return {
      userid: this.userid,
      username: this.username,
      age: this.age,
    };
  }
}

const user: User = new User(9382732, "A AI", 52, "ah@746Eo87R!");

// Convert class instance to JSON
const jsonString: string = JSON.stringify(user);

console.log("JSON String:", jsonString);



/*
run:

"JSON String:",  "{"userid":9382732,"username":"A AI","age":52}" 

*/

 



answered Dec 6, 2025 by avibootz
...