Ross McFarlane
Ross McFarlane

Reputation: 4254

Indent JSON on save in Vim

I'm using elzr/vim-json for JSON, which works very nicely. gg=G indents JSON, and doesn't destroy my buffer if it contains invalid JSON.

Is there a way that I can run gg=G on save, but only for JSON files?

Upvotes: 2

Views: 747

Answers (1)

Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9117

I guess that you are looking for autocmd:

:autocmd BufWritePre *.json :normal gg=G

You can add this line to your vimrc and gg=G will be applied to every file matching the *.json pattern on save.

Alternatively, you can use python -m json.tool to indent your JSON file:

:autocmd BufWritePre *.json execute '%!python -m json.tool' | w

This command will lint you code using an external command (python -m json.tool) and save it to the current buffer (w).

Upvotes: 6

Related Questions