faceag
Last Updated: October 14, 2018
·
93.21K
· 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

4827

Awesome sauce!

over 1 year ago ·
5396

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

over 1 year ago ·
8215

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 ·
11021

Even simpler:

com! FormatJSON %!python -m json.tool

Usage:

:FormatJSON
over 1 year ago ·
13422

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 ·
16079

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

over 1 year ago ·
18171

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

over 1 year ago ·
20918

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

over 1 year ago ·
28295

Try gg=G

over 1 year ago ·
28604

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 ·
28781

is there possibility to convert back to compact format?

over 1 year ago ·
28816

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 ·
29171

@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 ·
29505

Thanks for this

10 months ago ·
30978