Skip to content
8-bit Jason Voorhees

Formatting JSON.stringify()

Monday, May 10, 2021

At 342 words, this article should take about 2 minutes 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! 😃

Cover image courtesy of Hello I'm Nik.

Comments

In almost all cases, the comments section is a 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 Twitter (which is, in it's own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Banks

Thomas Banks

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online