Skip to content
8-bit Jason Voorhees

Formatting JSON.stringify()

Monday, 10 May 2021

At 213 words, this article should take about 1 minute to read.

This article is more than a year old and the information in it may be out of date.

I occasionally find myself dumping stringified JSON into a <pre/> tag in my markup. It inevitably looks horrible. In the spirit of If I write it down I won't forget it, here's how to prettify your JSON.stringify() output.

I always forget that JSON.stringify() takes three arguments:

  1. The given object
  2. An optional replacer
  3. An optional spacing count

You can find more detail on the MDN Web Docs for JSON.stringify but I'm getting into the habit of using this as my default stringify function…

JSON.stringify(obj, null, 2);

Adding that , null, 2, turns this…

Displayed stringified JSON without formatting

…into this…

Displayed stringified JSON with formatting


Remember that replacer? You can narrow down what is displayed by dropping an array of keys in there instead of null.

JSON.stringify(obj, ['phone'], 2);
Displayed stringified JSON partial with formatting


The data displayed in the above screenshots is provided by which is an API for generating user data. They describe themselves as Like Lorem Ipsum, but for people and they're a really useful resource. #notsponsored.

I used the ever useful QuokkaJS to run my JSON.stringify code. For those that don't know, Quokka.js is a developer productivity tool for rapid JavaScript / TypeScript prototyping and is available as a VS Code plugin. Again, not sponsored - just a fan! 😃

Cover image courtesy of Hello I'm Nik.



In almost all cases, the comments section is a vile cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).

Thomas Rigby

Thomas Rigby

When I'm not building things for the internet, I take photos of stuff.

Pronouns: he/him/his

Real. Simple. Syndication.

Get my latest content in your favorite RSS reader. I use InoReader but you don't have to.

What even is an RSS feed?!


Last played

Burn the Bitch

Ulver || Svidd Neger

Loading Invisible Visible RSS Navigation Close Arrow Info Online Online