Making a JSON prettifier in pure JavaScript

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, December 20, 2019

Follow me on Twitter as @mattiasgeniar

A few weeks ago I toyed with the idea of making a JSON prettifier myself. I often use these to re-format and debug a minified JSON payload.

I don’t want to trust external web-based tools (and don’t always want to open up an editor to format it), so like most of my projects I decided to write one myself.

And since this is a purely static website, I’m limited to JavaScript.

What I thought would be a fun coding challenge turned out to be … quite boring.

Formatting a JSON body takes just 3 lines of JavaScript.

json = JSON.parse(input);

result = JSON.stringify(json, null, 4);    // stringify with 4 spaces at each level

resultsDiv.innerHTML = result;

This gets the JSON input from a textfield, parses it and through the magic of stringify() it gets pretty-printed straight away.

You can use this tool right here: JSON prettifier. It happens purely client-side and I don’t store any of the input.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.