Trick of the Day: one line vim nmap to beautify bloody Json monster

Vim Trick    Learn and Write

nmap =j :%!python -m json.tool<CR>

Trick of the day to this line of magic.

I am recently taking over some work from a colleague, and I was experimenting his code base. Suddenly, I got a giant unformatted json dump. Not surprising, haha; As always, we need to beautify it to have it more readable.

One quick way, I was taught by my previous lead, was beautifying with json module in interactive python shell. Namely: open python interactively, then do the trandformation and save beautified json.

However, I was in vim, and it occur to me that given the powerfulness of vim and there are so many geeks around vim, there must be a trick that will just do in file json formatting. Then, I go the following result from search:

:%!python -m json.tool

Essentially, logic of this trick under the hood is same as the native way I mentioned. However, it is way shorter in terms of steps needed.

This solve the 99.9% of our immediate need to just format the json currenly in front you on screen. However, this line is hard to remember and type it out later when needed. It became a natural call to make a vim mapping for the line. Finally, I got the following:

nmap =j :%!python -m json.tool<CR>

This is a great mapping suggestion from a comment of the original solution. The main consideration of having =j is because = is known to vim world as formatting/indenting. It then become obvious and easy to remember to have =j dedicated for json beautifying!

Enjoy and Cheers!


comments powered by Disqus