Format JSON in Vim with jq
Contents
- Introduction
- The jq command
- Set keymaps
- Create AutoCommand
- Set as Vim’s default formatter
- Conclusion
Introduction
You can run external commands like sort
, echo
, git
, etc. in Vim command-mode.
With jq installed, you can run jq
command and format JSON files inside Vim.
The jq command
:%!jq
Format (pretty-print) code in file.
:.!jq
Format code in current line.
:%!jq -c
Compact output with -c
or --compact-output
flag.
Check jq
man page for more.
%
represents current file, while .
represents current line.
Set keymaps
If you frequently run these commands, you can bind them to a key.
For example, map CTRL+J to run the :%!jq
command in Vim:
noremap <C-j> :%!jq<CR>
The same binding for Neovim in Lua:
vim.keymap.set('n', '<C-j>', ':%!jq<CR>', {desc="Pretty-print JSON"})
Create AutoCommand
Another cool trick would be to create an AutoCommand
to automatically run these commands on file write.
Here’s how to set one in Neovim:
-- Auto format JSON on write
vim.api.nvim_create_autocmd('BufWritePre', {
group = vim.api.nvim_create_augroup('format-file', {}),
pattern = '*.json',
command = ':%!jq'
})
Set as Vim’s default formatter
Pressing gq + motion
formats file using Vim’s built in format program.
We can set jq
as the default format program for JSON files with:
set formatprg="jq"
.
Conclusion
You can lookup and use different formatters for different file types. The possibilities are limitless in Vim.