Pretty Json Stringify đź’…

TIL — 26.03.2018

Jonas
arkulpa
3 min readApr 24, 2018

--

Due to the fact that I learn small but exciting things almost every day and tend to forget too much about this stuff too fast I decided to write them down as TIL articles and share them with you.

Without further ado lets discover an amazingly simple thing a colleague showed me today. Thank you very much Torsten Hain.

Thanks Kirill Grouchnikov for the reference.

Unfortunately this image mirrors my usual development pretty accurate (and I’m sure I’m not the only one) but if we do non optimal things why not at least do them pretty? 💅

Disclaimer: The pretty emoji is obviously stolen from styled-components.
Thanks Max Stoiber.

I have a lot of use cases where I log stuff. For example I inspect the state of an object or a value, use the output as mock in my code, send it to colleagues or use it in documentation.

Almost always I need an illustrative representation which is easy to observe.
My usual workflow till today was to log the stringified version, copy it in some kind of formatter and use the prettified result.

Example of simple usage of JSON.stringify

Apart from the obvious drawback of repeating the same work over & over again this also has other cons you have to keep in mind.
If you use an online tool (like this json formatter) you may want to omit any secrets you don’t want to send to an external service. These are sometimes hard to find in the unformatted json even if you haven’t forgotten to think about removing them in the first place.
As alternatives you can use a local formatter, the auto format feature of your favorite IDE (which is a hard choice on its own) or use Prettier to format your code IDE agnostic.

In browsers where you have an interactive console (in contrast to for example node logs) the need is sometimes not that urgent because you can expand an object layer by layer.
But even there I often stringify a logged object via the Chrome feature »Store as global variable« and JSON.stringify(temp1).

Example of using »Store as global variable«

Now lets reveal the amazingly simple secret I learned today. 🔑
The stringify function does take more than one argument. With the third argument it is possible to specify the spacing which results in a formatted json output. đź’…

Example of an amazingly simple change which results in formatted JSON.stringify output

It is also possible to specify a string as spacing if you need a more advanced usage. For completeness the second argument lets you pass a replacer function which allows to omit or replace properties in the result.
To learn more details you can always reference to the documentation.

Jonas Hackenberg — jonas@arkulpa.at — www.arkulpa.at

*

Thanks for reading my first TIL article. If you enjoyed it don’t hesitate to clap & comment your thoughts. I hope to continue this series and present a lot of other interesting learnings. 👏

--

--