faceag
Last Updated: February 13, 2017
·
47.3K
· kennu
F8828772ff141a7cb8fe109af7948da1

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/

10 Responses
Add your response

4827
C0cb9a130496b9d5dd2362e818c66014

Awesome sauce!

over 1 year ago ·
5396
E94a065789007e8c3301ae1d726e6537

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
Aec924d6fd4f693e4a93c1f463c5023a

Even simpler:

com! FormatJSON %!python -m json.tool

Usage:

:FormatJSON
over 1 year ago ·
13422
811d61a875dcc509c6a5e841f5305b16

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
62bba59f4b7347e613597e1826a5339d

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

over 1 year ago ·
18171
8e9e135bb9e8b1827ceaf690f9a9e5c3

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

over 1 year ago ·
20918
Pietervogelaar square 1300

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

4 months 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.

10 days ago ·