DEV Community

Cover image for Quickly format and manipulate JSON in vim using jq
Miha Filej
Miha Filej

Posted on

Quickly format and manipulate JSON in vim using jq

Ever needed to check whether the JSON you just wrote is valid? Or wanted to quickly rename keys in a JSON array?

There are two components worth understanding that we will later put together.

First, a brief introduction to jq — a wonderful tool for manipulating JSON on the command line — like sed for JSON data as the official website describes it. It is truly powerful and able to manipulate JSON in a myriad of ways. When run with no arguments, it simply formats the given document:

$ echo '{ "foo":   "bar"     }' | jq
{
  "foo": "bar"
}

Enter fullscreen mode Exit fullscreen mode

Second, vim allows you to pipe the contents of the current buffer into a unix command. The command for passing the current buffer through jq would be:

:% !jq
Enter fullscreen mode Exit fullscreen mode

Combining the two, we get a convenient way to format JSON, or really, manipulate the contents of a buffer in any way (another example I use often is sorting through !sort).

A screen recording showing the described technique in action

How about manipulating JSON? Let's look at two simple examples using the same JSON document. The following command will rename the "size" key to "variant":

:%!jq '.items |= map(.variant = .size | del(.size))'
Enter fullscreen mode Exit fullscreen mode

How about uppercasing every value in an array? Easy enough:

:%!jq '.items |= map(.variant |= ascii_upcase)' 
Enter fullscreen mode Exit fullscreen mode

Savvy vim users will recognize that % is in essence just a way to tell vim to use every line in a buffer (see :help :%). We can just as easily use a subset of the buffer, either by specifying the line numbers explicitly or using visual selection (shift-v):

A screen recording showing how to pipe part of a buffer to a unix command

That's it! I hope this technique can streamline your workflow and make you a more efficient vim user.

Bonus: a GPT-generated haiku about vim and the unix pipeline:

Vim sharp as a knife
Unix pipeline, ever wise
Together they thrive

Top comments (0)