The vi editor has been around since the mid 1970's. It is still the most widely used text editor on UNIX/Linux systems. In the early nineties vim (vi improved) was released as a clone for vi with additional improvements. With an abundance pf plugins and the ability to use external programs to further expand it's capability, there seemingly unlimited potential. In this Linux quick tip we will be discussing how to format a json object in vim.

Using jq To Format JSON in Vim

The jq program is a filter that takes input and produces and output.

jq filters run on a stream of JSON data. The input to jq is parsed as a sequence of whitespace-separated JSON values which are passed through the provided filter one at a time. The output(s) of the filter are written to standard out, again as a sequence of whitespace-separated JSON data.

Excerpt from js manual on Github

You can install the jq program with your systems package manager. Below are examples of how to install it on most popular Linux distributions.

# Fedora
sudo dnf install jq

# Ubuntu / Debian
sudo apt install jq

# CentOS / RedHat 
sudo yum install jq

NOTE: For Red Hat/CentOS systems you may need to enable the epel repository first.

Alternatively, you can install it as a snap from the Snap Store.

Once you have it installed, simply open your json file in vim and use :%!jq . to format it into a human readable form.

Formatting json in vim with jq

Below we have formatted the command in the jq example for clarity.

:%!jq .

Use Python to Format JSON in vim

If you are more comfortable with Python this is a good option for you. Python comes preinstalled on most Linux distributions. Therefore there is no need to install additional packages.

To format json in vim using python simply open the file and give the :%!python -m json.tool command.

formatting json in vim with python


There are multiple methods available for people looking to format json in vim. If you are going to use this often I suggest you do some research. There are multiple plugins available for developers. However, these methods are usually fine for a single run or one-off need.

Resources and Further Reading