Skip to content

Apologies for the appearance of the site. I'm designing in public!

8-bit Jason Voorhees

Formatting JSON.stringify()

Published on Monday, 10 May 2021.
At 200 words, this article should take about 1 minute to read.

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

Bonus

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

Credits

The data displayed in the above screenshots is provided by randomuser.me 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! 😃


Fin

Cover image courtesy of Hello I'm Nik.

Comments

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).

onward-journeys module