Search code examples
jsonvimformatlint

How to auto format JSON on save in Vim


To be honest go has spoiled me. With go I got used to having a strict formatting standard that is being enforced by my editor (vim) and is almost accepted and followed by everybody else on the team and around the world.

I wanted to format JSON files on save the same way.

Question: How to auto format/indent/lint json files on save in vim.


Solution

  • Thanks mMontu and Jose B, this is what I ended up doing:

    WARNING this will overwrite your buffer. So if you OPEN a json file that already has a syntax error, you will lose your whole file (or can lose it).

    Add this line to your ~/.vimrc

    " Ali: to indent json files on save
    autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool
    

    you need to have python on your machine, of course.

    EDIT: this next one should not overwrite your buffer if your json has error. Which makes it the correct answer, but since I don't have a good grasp of Vim script or shell for that matter, I present it as an experimental thing that you can try if you are feeling lucky. It may depend on your shell too. You are warned.

    " Ali: to indent json files on save
    autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool 2>/dev/null || echo <buffer>