Skip to content

Woohah, tremendous improvements to the inspect helper

Compare
Choose a tag to compare
@thetutlage thetutlage released this 02 May 16:41

In order to print server side objects in the browser, you need to convert them to a string, since you cannot send a Javascript primitives over HTTP.

Many individuals opt for JSON.stringify(someObj) to convert an object to its string representation and then print it in the browser. In fact, many template engines provides helpers for JSON.stringify. For example: nunjucks

Problems with JSON.stringify

The stringify method cannot represent all of the Javascript data types. It includes Maps, Sets, BigInt and so on.

More importantly, the output of JSON.stringify is not a true representation of an object and can trick you many times. For example:

You have the following class

class User {
  constructor() {
    this.options = {
      timezone: 'UTC',
      theme: 'dark'
    }

    this.attributes = {
      username: 'virk',
      email: 'virk@adonisjs.com'
    }
  }

  toJSON() {
    return this.attributes
  }
}

If you print an instance of this class using console.log, you will get the desired outcome

console.log(new User())

// User {
//   options: {
//     ...
//   },
//   attributes: {
//    ...
//   }
// }

However, with JSON.stringify, you get the following output.

console.log(JSON.stringify(new User()))

// '{"username":"virk","email":"virk@adonisjs.com"}'

Where are the attributes and options properties?

Well, the JSON.stringify method recursively calls .toJSON method on the objects you pass. So, when the user instance it passed to JSON.stringify method, it returns the output of user.toJSON.

This is not a problem with JSON.stringify, since this method is not meant to inspect native data types. It is meant to serialize/deserialize them.

The console.log method of Node.js doesn't use JSON.stringify, it uses util.inspect. The util.inspect method is great for dump the output in a terminal, but not in a browser.

Edge inspect helper

With this release, the edge inspect helper works similar to console.log/util.inpsect, but the output is tailored for browser with support for pretty printing.

Usage

Write the following code inside any template file.

{{ inspect(state) }}

Output

Screen Shot 2020-05-02 at 9 18 57 PM

Commits

  • fix(inspect): do not use JSON.stringify for inspecting objects 8fc7e95
  • improvement(inspect): handle circular references and allow custom inspection ddd5541

v3.0.2...v3.0.3