Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 891
Ali Avatar asked Oct 06 '14 10:10

Ali


People also ask

How do I auto format a JSON file?

The key-map to auto-format the selected JSON is ALT-SHIFT-F. This is the same key-map to auto-format other languages too, so I often find myself doing CTRL-A (for select all text) followed by ALT-SHIFT-F to fix my messy C# code after a series of cut and paste operations.

What is the correct format of a JSON file?

JSON files are stored with the . json extension. JSON requires less formatting and is a good alternative for XML. JSON is derived from JavaScript but is a language-independent data format.


1 Answers

In one command, try this:

execute '%!python -m json.tool' | w   

You could then add you own key binding to make it a simpler keystroke. Of course, for this to work, you need to have Python installed on your machine.

like image 124
Jose B Avatar answered Oct 03 '22 15:10

Jose B