Vim command to format JSON file:
:%!python -m json.tool
Vim command to format JSON file:
:%!python -m json.tool
For further actions, you may consider blocking this person and/or reporting abuse
Aditya Pratap Bhuyan -
Hyldgaard Levin -
Jelena Petkovic -
Cristián Andrés -
Top comments (3)
Nice tip.
I don't work with
python
much, so I never remembered the syntax (e.g.python -m json
?python -m tool.json
? )Alternatively, other tools can do this too:
:%! prettier --parser=json
:%! jq
Regardless of the tool, you can create a function so you don't have to type long vim commands every time:
Now, you can format JSON with
: call Format()
.For added convenience, you can create a command for your custom function:
Now, you can format JSON more simply with
:Format
.For even more convenience, map the command to a keybinding:
Now, assuming your
<Leader>
is the default\
, you can format JSON even more simply with\F
.By the way, you don't need a function and a command to create a mapping. You can jump straight to it with
nnoremap <silent> <Leader>F :silent %! python -m json.tool<CR>
.Lastly, if you want to format on save experience:
Now, when you save any JSON file (
:w
) , it will auto format.Bonus Tip
Vim has built-in formatting system (
:help 'formatprg'
). So, you can set this option based on filetype (e.g.json
,python
...etc) and use thegq
command (:help gq
) to format.Example:
In your
.vimrc
:Then, when you want to format a python file (assuming your cursor is at the top of the file):
gqG
(explanation:gq
is the command and it expects a{motion}
, in this caseG
is the motion for "end of file"). For more on extending this to other filetypes, see my dotfiles.Happy vimming!
Thanks for the explanation.
I'll definitely try
built-in formatting system
.Also, thanks for adding your dotfiles link.
No problem.
The link to the dotfiles points to
master
branch which is no longer accurate.Here is the correct commit link to my vimrc: github.com/pbnj/dotfiles/blob/5dc8...
Inspired by: github.com/joereynolds/gq.vim