Pretty Print JSON in JavaScript

PROBLEM

You want to display a JSON object in JavaScript.

TAKE 1

console.log(json);

While this works, I find this approach inconvenient when viewing the output in Firebug because I have to click on each generated link to view the details.

TAKE 2

console.log(JSON.stringify(json));

… will generate this:-

[{"title":"Holiday","id":"a1","start":"2014-02-03T09:00:00.000Z","allDay":true},{"title":"Pay Day","id":"a2","start":"2014-03-31T08:00:00.000Z","allDay":true}]

This approach will display the entire JSON object as one long string. This is better than me clicking on each generated link, but this is still fairly unreadable and cumbersome to me if I have a large JSON object.

TAKE 3

console.log(JSON.stringify(json, null, '\t'));

… will generate this:-

[
	{
		"title": "Holiday",
		"id": "a1",
		"start": "2014-02-03T09:00:00.000Z",
		"allDay": true
	},
	{
		"title": "Pay Day",
		"id": "a2",
		"start": "2014-03-31T08:00:00.000Z",
		"allDay": true
	}
]

Aw snap… a nicely formatted JSON string.

Advertisements

One thought on “Pretty Print JSON in JavaScript

  1. John F

    THANK YOU!!!! I have been looking for this exact solution for longer than I care to admit. You are my hero today.

    Reply

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