Is there a way to pretty-print JSON in a web page using JavaScript?
Asked Answered
P

7

16

Seems to me that pretty-printing JSON is a simple enough task that JavaScript should be able to handle it. Has anyone ever written (or run across) a JavaScript function to do this?

Pliny answered 19/1, 2011 at 19:32 Comment(0)
P
1

What I ended up doing is installing the JSONView add-on for Mozilla. Not perfect, but it gets done what I needed done.

Pliny answered 14/4, 2011 at 15:25 Comment(0)
F
12

An easy way to do this is to execute:

JSON.stringify(data, null, "  ");

where data is the json object you want to print pretty.

Not every browser contains JSON though. You can include json.js by Douglas Crockford which add global JSON object if it is not supported natively by the browser.

Fleshly answered 2/4, 2011 at 15:11 Comment(2)
JSON.stringify is not terribly pretty, even with extra spaces. I found the vkbeautify link below to be a great solution.Rizas
this seems like a bad solution, since subsequent calls to pretty print JSON might be then bastardizedKeratosis
B
8

I use this bookmarklet code on my browsers to make the JSON paragraph readable

javascript:(function(){document.body.firstChild.innerHTML = JSON.stringify(JSON.parse(document.body.firstChild.innerHTML), null, 4);})();

Adding a bookmarklet is easy - right click on bookmarks bar - Add/New - provide a name and paste js in url / location box

As current day browsers are putting the json response in a <pre> tag inside, i use body.firstChild

Balustrade answered 27/8, 2016 at 16:22 Comment(1)
This is awesome, still working in 2023 (if you ignore the word 'bookmarklet') !Agneta
P
3

take a look at vkbeautify.js plugin

http://www.eslinstructor.net/vkbeautify/

it provides pretty print for both JSON and XML text.

written in plain javascript, small and fast.

Puzzle answered 25/1, 2012 at 20:47 Comment(2)
I really liked this solution. It worked great with node and I see they also have a browser version.Rizas
Disclaimer: vkbeautify.json is a wrapper to JSON.stingifyPacific
D
1

JavaScript data formatting/pretty printer

Dunedin answered 19/1, 2011 at 19:35 Comment(0)
S
1

If you want this for yourself (debugging purposes) you can use Greasemonkey: http://misc.slowchop.com/misc/wiki/HumanReadableJSONGreasemonkey

If you want the output for your users: http://jsonformatter.curiousconcept.com/

Swollen answered 19/1, 2011 at 19:36 Comment(0)
P
1

What I ended up doing is installing the JSONView add-on for Mozilla. Not perfect, but it gets done what I needed done.

Pliny answered 14/4, 2011 at 15:25 Comment(0)
L
1

You can give this a try it will add in some nice CSS.

<pre style="font-family: Courier;background: #f4f4f4;border: solid 1px #e1e1e1;float: left;width: auto;">
    JSON.stringify(data, null,' ').replace('[', '').replace(']', '')
</pre>
Longoria answered 7/9, 2016 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.