How to format JSON file using Vim?

sample json formated file

Did you ever used Vim editor? You like it? Ohhh… If answer is yes, then you know how to use vim editor or you know well known features of Vim. Anyway, I assume that you are familiar with Vim. If not then don’t worry ! Try it on your free time. Now let’s talk about JSON.

I guess you already know JSON right ? JSON mean JavaScript Object Notation. It’s a one of the best way to store data in structure. Sample JSON object you can find below…

    "id": 1,
    "first_name": "Celene",
    "last_name": "Fleisch",
    "email": "",
    "gender": "Female",
    "ip_address": ""
    "id": 8,
    "first_name": "Blondell",
    "last_name": "Gergus",
    "email": "",
    "gender": "Female",
    "ip_address": ""

That above sample JSON object looks pretty. But today, I have to look one of json data file and when I opened file in vim… Ohhh everything looks ugly ! So, before starting work with json file, I need to make those json data in pretty format. I was started googling. And find out one simple command, that give me pretty view of JSON object. Look, once it json is formated you can save it. Formatting json file, fire below command in your vim and that’s it ! Try it.

json object
json object
Vim command :
:%!python -m json.tool

Let’s take a look and understand how command is made:

: – Brings you from Normal Mode into Command-Line Mode. Vim now waits for you to enter a command.
% – It’s a symbolic identifier to specify a range. It’s a range from the first to last line of the current buffer. You could also specify line numbers like 2,5 which defines the range from line 2 to line 5. Another possible way to define a range is to use Visual Mode.
! – For let you run any Unix shell command.
python -m json.tool – The actual shell command. Here we run a Python library module json.tool that does the actual work for us. The output of this command is sent back to your Vim buffer once executed.

That’s it ! Vim is awesome text editor.