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

1 Answer

0 votes
class User {
    constructor(username, age, userid, password) {
        this.userid = userid;
        this.username = username;
        this.age = age;
        this.password = password; // should not be serialized
    }
    toJSON() {
        // Exclude data like id
        return {
            userid: this.userid,
            username: this.username,
            age: this.age
        };
    }
}

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

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

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



/*
run:

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

*/

 



answered Dec 6, 2025 by avibootz
...