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"
}
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
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
).
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))'
How about uppercasing every value in an array? Easy enough:
:%!jq '.items |= map(.variant |= ascii_upcase)'
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
):
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)