Making a JSON prettifier in pure JavaScript

Tired of the privacy invasion of browsers? Worried about the risk of seeing ads everywhere? Give the Brave Browser a try. All Chrome extensions are compatible. None of the telemetry. Auto-blocks ads and still support content creators like me.

Download the Brave browser now »

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.