Node.js — Human-Readable JSON.stringify() With Spaces and Line Breaks

Code Sample

Serializing JavaScript to JSON is useful in various situations. Calling JSON.stringify(data) returns a JSON string of the given data.

This JSON string doesn’t include any spaces or line breaks by default. It’s hard to read when writing the serialized JSON to a file. What you can do is insert spaces for readability purposes!

Node.js Series Overview

Add Spaces and Line Breaks to JSON

JSON.stringify() accepts three arguments: the data, a replacer, and the space. This tutorial focuses on the space argument.

Pass in a number representing the space characters to insert white space. Common values are 2 or 4 and JavaScript automatically limits this to 10 spaces.

const data = {  
  name: 'Marcus',
  passion: 'Future Studio',
  likes: [
    {
      tag: 'Node.js',
      level: 10
    }
  ]
}

console.log(  
  JSON.stringify(data, null, 2)
)

This will serialize the data object to the following JSON:

{
  "name": "Marcus",
  "passion": "Future Studio",
  "likes": [
    {
      "tag": "Node.js",
      "level": 10
    }
  ]
}

This is way more human-readable than the simplistic default behavior without any spaces. Here’s what the serialized JSON looks like without spaces:

{"name":"Marcus","passion":"Future Studio","likes":[{"tag":"Node.js","level":10}]}

When working with large objects or data in files spaces in your JSON are helpful to keep track of the data in your application.

Enjoy coding & make it rock!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.