Dev HelpersOpen library
← Back

Customize JSON serialization

Customize JSON serialization in JavaScript.

Open this example in the interactive library

Source code

class User {
  constructor(name, internalId) {
    Object.assign(this, { name, internalId });
  }
  toJSON() {
    return { name: this.name };
  }
}
console.log(JSON.stringify(new User("Ada", 7)));

Sample output

{"name":"Ada"}