DEV Community

Damanpreet Singh
Damanpreet Singh

Posted on

Format JSON in vim

Vim command to format JSON file:

:%!python -m json.tool
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
pbnj profile image
Peter Benjamin (they/them)

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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=
Enter fullscreen mode Exit fullscreen mode

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!

Collapse
 
fumblehool profile image
Damanpreet Singh

Thanks for the explanation.

I'll definitely try built-in formatting system.
Also, thanks for adding your dotfiles link.

Collapse
 
pbnj profile image
Peter Benjamin (they/them) • Edited

No problem.

The link to the dotfiles points to master branch which is no longer accurate.

Here is the correct commit link to my vimrc: github.com/pbnj/dotfiles/blob/5dc8...

Inspired by: github.com/joereynolds/gq.vim