Last Updated: October 22, 2022
·
198.5K
· kennu

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/

15 Responses
Add your response

Awesome sauce!

over 1 year ago ·

nice! but I'm too lazy to learn how to make this a vim macro in my vimrc file.

over 1 year ago ·

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

over 1 year ago ·

Even simpler:

com! FormatJSON %!python -m json.tool

Usage:

:FormatJSON
over 1 year ago ·

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.

over 1 year ago ·

This is great. And @paddle's key map is great too.

over 1 year ago ·

how do I set indent size = 2 spaces instead of 4 ?

over 1 year ago ·

cat $FILE | python -c "import json, sys; print json.dumps(json.load(sys.stdin), indent=2)" > $FILE.tmp

over 1 year ago ·

Try gg=G

over 1 year ago ·

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.

over 1 year ago ·

is there possibility to convert back to compact format?

over 1 year ago ·

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.

over 1 year ago ·

@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.

over 1 year ago ·

Lets say i wanted to convert back to compact format what are the steps i should follow?

over 1 year ago ·

Perfect!

over 1 year ago ·
  NODES
Community 1
iOS 2
Javascript 3
mac 1
os 6
text 1
visual 1
web 1