Enhance JSON String Readability with this Simple JavaScript Hack

Boost JSON String Readability with a Quick JavaScript Tip

Developers often face the scenario where they deal with a substantial JavaScript object crafted on the front-end. But, before sending it to a REST endpoint, they aim to ensure its validity through validation. Typically, this is done by logging the object on the browser console and prettifying it. Let's understand this with an example

Example

Consider a case where you have a javascript object with a decent number of properties

let employee = {
    firstName: "Nirav",
    middleName: "Manish",
    lastName: "Soni",
    birthDate: new Date("January 1, 1982"),
    department: "Engineering",
    numYearsEmployment: 7,
    isActive: true,
    salary: 100000,
    joiningDate: new Date("December 1, 2016"),
    annualLeaves: 30,
    vacationLeaves: 30,
    isEligibleForESOP: true,
    isRemote: true
}

So, to convert it to JSON, the easiest way is to use the JSON.stringify method

Let's say when we execute this method against this employee object that we've defined at the top, we see this output

// Convert to JSON string
console.log(JSON.stringify(employee));

Output

{"firstName":"Nirav","middleName":"Manish","lastName":"Soni","birthDate":"1981-12-31T18:30:00.000Z","department":"Engineering","numYearsEmployment":7,"isActive":true,"salary":100000,"joiningDate":"2016-11-30T18:30:00.000Z","annualLeaves":30,"vacationLeaves":30,"isEligibleForESOP":true,"isRemote":true}

This gets more and more ugly and un-readable as the number of properties within the object increases

Is there a better way to view this JSON? - YES!

There are multiple overloads of the stringify method - See below

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)

The one we can use to serve our purpose is JSON.stringify(value, replacer, space) method

Testing the overloaded method

console.log(JSON.stringify(employee, null, 2));

Output

{
  "firstName": "Nirav",
  "middleName": "Manish",
  "lastName": "Soni",
  "birthDate": "1981-12-31T18:30:00.000Z",
  "department": "Engineering",
  "numYearsEmployment": 7,
  "isActive": true,
  "salary": 100000,
  "joiningDate": "2016-11-30T18:30:00.000Z",
  "annualLeaves": 30,
  "vacationLeaves": 30,
  "isEligibleForESOP": true,
  "isRemote": true
}

And now, we have a neat pretty looking formatted JSON string which is much easier to read and interpret!