How to format a JSON file in vim

When it comes to file formatting vim is pretty powerful. There are a couple of way you can format a JSON file in vim.

Option 1: Use jq (command line JSON processor)

jq is a must-have tool when working with JSON. It’s a powerful command line tool that allows you to map, filter, modify and format JSON data. It has a lot of functionality but the one we are going to use today is JSON pretty print. Or JSON formatting.

Install jq

You can download the latest binary from the official page https://stedolan.github.io/jq/

Alternatively you can install via package management tools based on the operating system you are on.

Windows

choco install jq

Mac OS

brew install jq

Linux

sudo apt-get install jq

Use jq in vim to format a JSON file

While you have vim opened on the JSON file you want to format you can run the following command

(Assuming you opened the json file)

vim file.json

Run the following to format the JSON file using vim

:%!jq .

This will run the jq command line utility over the JSON file contents you have opened with vim. It will rewrite the JSON data formatted into the same file. You will have to save your changes by using :w

Option 2: Use python json.tool module

Python offers off the shelf a tool to format JSON data. You can find more info about json tool module here https://docs.python.org/3/library/json.html

Here’s a couple of examples on how you can format a JSON file using python and/or vim

Just by using Python

python -m json.tool file.json

Using Python json tool from within vim

:%!python -m json.tool

This will run the json pretty print on the vim file you have opened and will rewrite the file with the new formatted JSON data. You will have to save your changes by using :w

Join the Golang Developers Community on Golang Cafe