loading...

Format JSON in vim

fumblehool profile image Damanpreet Singh ・1 min read

Vim command to format JSON file:

:%!python -m json.tool

Discussion

pic
Editor guide
Collapse
petermbenjamin profile image
Peter Benjamin

Nice tip.

I don't work with python much, so I never remembered the syntax (e.g. python -m json? python -m tool.json? )

Alternatively, other tools can do this too:

  • Using prettier: :%! prettier --parser=json
  • Using jq: :%! jq

Regardless of the tool, you can create a function so you don't have to type long vim commands every time:

function! Format() abort
  silent ! clear
  silent %!  python -m json.tool
endfunction

Now, you can format JSON with : call Format().

For added convenience, you can create a command for your custom function:

function! Format() abort
  silent ! clear
  silent %!  python -m json.tool
endfunction

command! Format :call Format()

Now, you can format JSON more simply with :Format.

For even more convenience, map the command to a keybinding:

function! Format() abort
  silent ! clear
  silent %!  python -m json.tool
endfunction

command! Format :call Format()

nnoremap <silent> <Leader>F :Format<CR>

Now, assuming your <Leader> is the default \, you can format JSON even more simply with \F.

By the way, you don't need a function and a command to create a mapping. You can jump straight to it with nnoremap <silent> <Leader>F :silent %! python -m json.tool<CR>.

Lastly, if you want to format on save experience:

autocmd BufWritePre *.json call Format()
" or
" autocmd BufWritePre *.json silent %! python -m json.tool

Now, when you save any JSON file (:w) , it will auto format.

Bonus Tip

Vim has built-in formatting system (:help 'formatprg'). So, you can set this option based on filetype (e.g. json, python ...etc) and use the gq command (:help gq) to format.

Example:

In your .vimrc:

autocmd FileType python setlocal formatprg=yapf | setlocal formatexpr=

Then, when you want to format a python file (assuming your cursor is at the top of the file): gqG (explanation: gq is the command and it expects a {motion}, in this case G is the motion for "end of file"). For more on extending this to other filetypes, see my dotfiles.

Happy vimming!