How to auto format JSON on save in Vim

In one command, try this:

execute '%!python -m json.tool' | w  

You could then add you own key binding to make it a simpler keystroke. Of course, for this to work, you need to have Python installed on your machine.


If you are keen on using external tool and you are doing some work with json, I would suggest using the jq:

https://stedolan.github.io/jq/

Then, you can execute :%!jq . inside vim which will replace the current buffer with the output of jq.


%!python -m json.tool

or

%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), ensure_ascii=False, indent=4)"

you can add this to your vimrc:

com! FormatJSON %!python -m json.tool

than you can use :FormatJson format json files


Thanks mMontu and Jose B, this is what I ended up doing:

WARNING this will overwrite your buffer. So if you OPEN a json file that already has a syntax error, you will lose your whole file (or can lose it).

Add this line to your ~/.vimrc

" Ali: to indent json files on save
autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool

you need to have python on your machine, of course.

EDIT: this next one should not overwrite your buffer if your json has error. Which makes it the correct answer, but since I don't have a good grasp of Vim script or shell for that matter, I present it as an experimental thing that you can try if you are feeling lucky. It may depend on your shell too. You are warned.

" Ali: to indent json files on save
autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool 2>/dev/null || echo <buffer>

A search for JSON plugins on vim.org returned this:

jdaddy.vim : JSON manipulation and pretty printing

It has the following on description:

gqaj "pretty prints" (wraps/indents/sorts keys/otherwise cleans up) the JSON construct under the cursor.

If it does the formatting you are expecting then you could create an autocmd BufWritePre to format when saving.