Embracing the Messiness in Search of Epic Solutions

Pretty Print JSON in JavaScript

Posted

in

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.

Comments

2 responses to “Pretty Print JSON in JavaScript”

  1. John F Avatar
    John F

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

  2. Olivia Avatar

    This is good, it help me save tons of time and I validate it using this tool https://jsonformatter.org/json-pretty-print

Leave a Reply