Easily format JSON in Vim
Nowadays we work a lot with JSON data. I had an API documentation with a lot of JSON samples. However the samples were all unformatted. So I tried to find an easy way to format them inside Vim.
There are some blog posts out there alread with this trick. But I like to write about things again to keep them in my repository and to remember them better.
Formatting a JSON file
If you have a JSON file you can use Python’s json.tool to format the whole document like this:
:%!python -m json.tool
type this in normal mode in vim. The
: will let you enter a vim command,
% will select the current file,
! will execute the following command on the shell.
The nice thing is that the current buffer will be overwritten by the results of the shell command. In this case the formatted JSON document.
Formatting JSON inside a text file
But what if we do not have a whole JSON file but e.g. a Markdown file with some JSON inside? Well, we can select the JSON lines in visual mode (<shift>+v) first.
When we press
: now to enter a command it changes automatically to this:
and we can enter the same command at the end like this:
:'<,'>!python -m json.tool
Et voilà! We have our JSON line(s) properly formatted.
This works with any range in Vim.