← til

Pretty formatting JSON in Vim

January 26, 2019
vim

I've explained how I've discovered json_pp in a previous TIL post, but I've discovered another great tool for the job, with the shorter name.

It's called jq and it blows my mind. You probably already have it installed on your machine. It's bascially sed for JSON. Its man pages describe pretty formatting of JSON as the most boring job it can do, so it's pretty powerful. You can check the examples on its tutorial page and see everything it can do on its manual page.

After you have it installed, you can pretty format that large chunk of JSON straight from Vim.

Let's say your cursor is on this line in your buffer:

{"foo":"bar","wat":"lol","user":{"name":"Bugs Bunny","address":{"street":"underground street","city":"acme town"}}}

Issuing this command will pretty format the JSON from the current line and replace it:

:.!jq .

Which results in:

{
  "foo": "bar",
  "wat": "lol",
  "user": {
    "name": "Bugs Bunny",
    "address": {
      "street": "underground street",
      "city": "acme town"
    }
  }
}

If you'd like to put the output to another buffer, you can do this instead:

:.w !jq .

So to achieve feature parity with my previous TIL post, all I needed to do to pretty format and copy that JSON was:

:.w !jq . | pb_copy

Sending current line from a buffer as an input to an external command is as easy as that! How great is that!?