Pretty-printing JavaScript objects with JSON.stringify

It’s fairly frequent that we end up wanting to log what the contents of a JS variable is. Often times though, that ends up being an object.

Frequently this leads to something like this:

var user = {
  first: 'John',
  last: 'Doe',
  age: 42
};

// plain console log
console.log(user);

// or with interpolation:
console.log(`User: ${user}`);

This of course prints:

{ prop1: 'value1', prop2: 2 }

User: [Object object]

The interpolation just calls .toString() on the object, which isn’t useful. The plain console.log() is much better, but with a large object this can be hard to read because all the properties are on one line.


How can we make this look nice?

We can leverage JSON.stringify() here to make our objects nicely formatted for logging. There is a seldom-used 3rd parameter to stringify() that tells it to print the object with newlines and indentation. By passing a number, that many spaces will be used to indent each level of properties.

Change the above example to:

var user = {
  first: 'John',
  last: 'Doe',
  age: 42
};

// plain console log
console.log(JSON.stringify(user, undefined, 2));

// or with interpolation:
console.log(`User: ${JSON.stringify(user, undefined, 2)}`);

and now we get the nice looking output:

{
  "first": "John",
  "last": "Doe",
  "age": 42
}

User: {
  "first": "John",
  "last": "Doe",
  "age": 42
}

Much nicer!

Advertisements
Posted in JavaScript, Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

CodingWithSpike is Jeff Valore. A professional software engineer, focused on JavaScript, Web Development, C# and the Microsoft stack. Jeff is currently a Software Engineer at Virtual Hold Technologies.


I am also a Pluralsight author. Check out my courses!

%d bloggers like this: