Formatting JSON.stringify()
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:
- The given object
- An optional replacer
- 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…
…into this…
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);
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.
onward-journeys module
Real. Simple. Syndication.
Get my latest content in your favorite RSS reader.
I use InoReader but you don't have to.
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).