toJSON()

ES5+

A method that can be defined on an object to customize its JSON serialization.

Syntax

object.toJSON()

Return Value

any

The value to be serialized

Examples

JavaScript
const user = {
  name: 'John',
  password: 'secret',
  toJSON() {
    return { name: this.name };
  }
};
console.log(JSON.stringify(user));
Output:
// '{"name":"John"}'

Related Methods