JSON files are awesome because they store collection of data in a human-readable format. However, reading the JSON file can be a pain if the JSON file is minified.

Take this for an example:

Print Json
Minified JSON is difficult to read

A computer can easily read it. Even a human can still read it but if JSON file is properly formatted to display the content, it will be much easier. I mean JSON files are supposed to read like this after all:

Pretty Printed Json
Pretty Printed JSON is easier to read

You can use most text editor with some plugins to display it with proper formatting. However, if you are stuck to a terminal or if you want to do it in your shell script, things will be different.

If you got a minified file, let me show you how to pretty print the JSON file in Linux terminal.

Pretty print JSON with jq command in Linux

jq is a command line JSON processor. You can use it to slice, filter, map and transform structured data. I am not going in details about using jq command line tool here.

To use jq, you need to install it first. You can use your distribution’s package manager to install it. With universe repository enabled, you can install it on Ubuntu using the apt command:

sudo apt install jq

Once you have it installed, use it in the following manner to pretty print JSON file on the display:

jq . sample.json
Pretty Print Json Linux Terminal
Pretty printed JSON file

You may also tempt to use cat but I believe it one of the useless use of cat command.

cat sample.json | jq

Keep in mind that the above command will not impact the original JSON file. No changes will be written to it.

You probably already know how to redirect the command output to a file in Linux. You probably also know that you cannot redirect to the same file and the tee command is not guaranteed to work all the time.

If you want to modify the original JSON file with pretty print format, you can pipe the parsed output to a new file and then copy it to the original JSON file.

jq . sample.json > pretty.json
Pretty Printing Json Linux Terminal
Pretty printing JSON file in Linux Terminal

Bonus: Minify a JSON file with jq command

Let’s take a reverse stance and minify a well formatted JSON file. To minify a JSON file, you can use the compact option -c.

jq -c < pretty.json
Minify Json File Linux
Minified JSON file display

You can also use cat and redirection if you want:

cat pretty.json | jq -c

Using Python to pretty print JSON file in Linux

It’s more likely that you have Python installed on your system. If that’s the case, you can use it pretty print the JSON file in the terminal:

python3 -m json.tool sample.json
Pretty Print Json With Python
Pretty printing JSON with Python

I know there are other ways to parse JSON file and print it with proper format. You may explore them on your own but these two are sufficient to do the job which is to pretty print JSON file.

Similar Posts