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

  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js (Coming soon)
  27. Check if a String is Empty in JavaScript or Node.js (Coming soon)
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js (Coming soon)
  29. Left-Trim Characters Off a String in JavaScript or Node.js (Coming soon)
  30. Right-Trim Characters Off a String in JavaScript or Node.js (Coming soon)
  31. Lowercase the First Character of a String in JavaScript or Node.js (Coming soon)
  32. Uppercase the First Character of a String in JavaScript or Node.js (Coming soon)
  33. Prepend Characters or Words to a String in JavaScript or Node.js (Coming soon)
  1. Get Number of Seconds Since Epoch in JavaScript
  2. Get Tomorrow’s Date in JavaScript
  3. Increase a Date in JavaScript by One Week
  4. Add Seconds to a Date in Node.js and JavaScript
  5. Add Month(s) to a Date in JavaScript or Node.js
  6. Add Week(s) to a Date in JavaScript or Node.js
  7. Get the Current Year in JavaScript or Node.js
  8. How to Get a UNIX Timestamp in JavaScript or Node.js
  9. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js
  10. Add Days to a Date in JavaScript or Node.js
  11. Get Yesterday's Date in JavaScript or Node.js
  12. Add Minutes to a Date in JavaScript or Node.js (Coming soon)
  13. Add Hours to a Date in JavaScript or Node.js (Coming soon)
  14. Check If a Date Is Today in JavaScript or Node.js (Coming soon)
  15. Check If a Date is Tomorrow in JavaScript or Node.js (Coming soon)
  16. Check If a Date is Yesterday in JavaScript or Node.js (Coming soon)
  17. How to Format a Date YYYY-MM-DD in JavaScript or Node.js (Coming soon)

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.