Pretty printing JSON in Vim

Command Line

First, your going to want to get a good command line tool to pretty print JSON. Unfortunately, you can’t just do this.


apt-get install ppjson

However, to create `ppjson`, you can just do the following.


sudo sh -c 'echo python -mjson.tool  > /usr/local/bin/ppjson'
sudo chmod 755 /usr/local/bin/ppjson

Now you have a JSON pretty printer called `ppjson`. Just pipe some JSON into it and watch it go to work.


jhogan@abe:$ echo '{"b":2, "a":1}' | ppjson
{
    "a": 1,
    "b": 2
}

Doing it in Vim

Vim has a very nice feature that lets you pipe text from a Vim buffer into a filter (i.e., command). Lets say your Vim buffer is filled with unformatted JSON text – but nothing more. Just issue the following command-line in Vim’s command mode.

%!ppjson

The buffer will now be filled with nicely formatted JSON.

On the other hand, if only a portion of the Vim buffer contains JSON, use CTRL-V to select the JSON, then, while still in normal mode, type !ppjson. In Vim’s command line, you will see:


:'<,'>!json

Hit ENTER and the unformatted JSON will be replaced by formatted JSON.

Leave a Reply

Your email address will not be published. Required fields are marked *