Today I Learned

hashrocket A Hashrocket project

Pretty Print JSON/HTML in Vim

When working with external APIs often you will get a highly netsted json, like this one, all in one line, with no spaces:

{"batters":{"batter":[{"id":"1003","type":"Blueberry"},{"id":"1004","type":"Devil's Food"}]},"id":"0001","name":"Cake","ppu":0.55,"topping":[{"id":"5002","type":"Glazed"},{"id":"5007","type":"Powdered Sugar"}],"type":"donut"}

The horror. You are not a network cable! You deserve better!

Add the following to your .vimrc file:

command! PrettyPrintJSON %!python -m json.tool
command! PrettyPrintHTML !tidy -mi -html -wrap 0 %
command! PrettyPrintXML !tidy -mi -xml -wrap 0 %

Now you can paste the json into your Vim buffer and run the :PrettyPrintJSON command.

{
    "batters": {
        "batter": [
            {
                "id": "1003",
                "type": "Blueberry"
            },
            {
                "id": "1004",
                "type": "Devil's Food"
            }
        ]
    },
    "id": "0001",
    "name": "Cake",
    "ppu": 0.55,
    "topping": [
        {
            "id": "5002",
            "type": "Glazed"
        },
        {
            "id": "5007",
            "type": "Powdered Sugar"
        }
    ],
    "type": "donut"
}

Magic.

Same goes for HTML, just run :PrettyPrintHTML.

NOTE: For these to work you need to have python and tidy installed on your machine.

See More #vim TILs
Every developer at Hashrocket is a Vim expert. Check out our development environment, Dotmatrix, and if you are in Chicago, come to the Vim Chicago Meetup hosted at our Chicago office.