Create a Custom “toJSON” Function in Node.js and JavaScript

Serializing JavaScript objects and other data structures as JSON is useful for data exchange between a server and a client. The JSON data exchange between client and server doesn’t require a JavaScript stack on both ends. JSON support is typically available in most programming languages.

Node.js Series Overview

Creating a Custom toJSON Function

Web frameworks typically support JSON responses and will serialize the data structures for you. If you want to serialize the data manually in JavaScript and Node.js, you may use the JSON.stringify(data) method. The JSON.stringify() function is globally available in JavaScript.

In specific situations, you want to customize the JSON output. For example, you may want to add a computed property using other property in the object. Or you want to remove sensitive data like a user password before serializing a user object and sending it over the wire.

A Custom toJSON Function on Objects

JavaScript supports custom toJSON() functions on objects. When serializing an object, JavaScript looks for a toJSON() property on that specific object. If the toJSON() property is a function, then that method customizes the JSON serialization behavior. JavaScript will then serialize the returned value from the toJSON() method.

Here’s an example of a computer object. It describes a Macbook and how a custom toJSON() method may look like:

const macbook = {  
  name: 'Macbook',
  cpus: 1,
  cores: 4,

  toJSON: function () {
    return {
      name: this.name,
      cpus: this.cpus,
      hasCpus: !!this.cpus,
      cores: this.cores,
      hasCores: !!this.cores
    }
  }
}

JSON.stringify(macbook)  
// {"name":"Macbook","cpus":1,"hasCpus":true,"cores":4,"hasCores":true}

The toJSON() method returns an object with the three original properties and two more computed ones. The hasCpus and hasCores properties are based on the original ones.

A Custom toJSON Function in a Class

You can also customize the JSON serialization handling in JavaScript classes. Instances of a class in JavaScript are represented as objects. That means, a toJSON() method on that object affects the JSON creation.

Here’s a sample JavaScript class for a Computer providing a custom toJSON() method.

class Computer {  
  constructor({ name, cpus, cores }) {
    this.name = name
    this.cpus = cpus
    this.cores = cores
  }

  /**
   * Transforms the machine instance to a JavaScript object.
   *
   * @returns {Object}
   */
  toJSON() {
    return {
      name: this.name,
      cpus: this.cpus,
      hasCpus: !!this.cpus,
      cores: this.cores,
      hasCores: !!this.cores,
    }
  }
}

JSON.stringify(  
  new Computer({ name: 'Macbook', cpus: 1, cores: 4 })
)
// {"name":"Macbook","cpus":1,"hasCpus":true,"cores":4,"hasCores":true}

The created instance of the Computer class creates a JSON object with five properties. Originally, the instance had three properties but the custom toJSON() method adds two more.


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.