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 in Vim like sort
, echo
, git
, etc., in command-mode.
With jq installed, you can run jq
command and format JSON files inside Vim.
The jq command
Format (pretty-print) code in file: :%!jq
Format code in current line: :.!jq
Compact output with -c
or --compact-output
flag: :%!jq -c
Read the jq
man page for more commands.
In Vim, %
represents the current file, and .
represents the current line.
Set keymaps
If you frequently run these commands, you can bind them to a key.
For e.g., you can map CTRL+J to run the :%!jq
command in Vim like:
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'
})
Although, I would argue not to set automatic formatting like this as to avoid unexpected issues.
Set as Vim’s default formatter
Pressing gq + motion
formats file using Vim’s built in format program.
To set jq
as the default format program for JSON files with put the following in you config file:
set formatprg="jq"
.
Conclusion
You can lookup and use different formatters for different file types.