Format JSON in vim
Vim sometimes still amazes me. Editing a Django JSON fixture or some other uglily formatted JSON file, just say:
:%!python -m json.tool
And you have nice, human-editable JSON in your editor.
Via: http://blog.realnitro.be/2010/12/20/format-json-in-vim-using-pythons-jsontool-module/
Written by Kenneth Falck
Related protips
15 Responses
Awesome sauce!
nice! but I'm too lazy to learn how to make this a vim macro in my vimrc file.
Thanks! I defined a custom function my vimrc so I don't have to remember the command :) Here is what you have to add to your vimrc file.
function! FormatJSON()
:%!python -m json.tool
endfunction
Even simpler:
com! FormatJSON %!python -m json.tool
Usage:
:FormatJSON
My version:
nmap =j :%!python -m json.tool<CR>
Since =
is the VIM command to format text (but only in select or visual mode), I figured this would be easy to remember. All I have to do now is type =j
to format a JSON file. Neat.
This is great. And @paddle's key map is great too.
how do I set indent size = 2 spaces instead of 4 ?
cat $FILE | python -c "import json, sys; print json.dumps(json.load(sys.stdin), indent=2)" > $FILE.tmp
Try gg=G
Unfortunately it sorts the json alphabetically. is there a switch to prevent this sorting. I want to keep my document in it's original order.
Otherwise an absolutely amazing tool.
is there possibility to convert back to compact format?
jlb333333:
Unfortunately it sorts the json alphabetically. is there a switch to prevent this sorting. I want to keep my document in it's original order.
Otherwise an absolutely amazing tool.
Try
:%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), indent=4)"
Unfortunately, this adds a space at the end of every line. But that's simple enough to delete afterwards.
@lastorset:
Try
:%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, objectpairshook=collections.OrderedDict), indent=4)"
Thank you.
Initial tests look good.
Still testing for use cases.
Lets say i wanted to convert back to compact format what are the steps i should follow?
Perfect!