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:
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:
You can use most text editors with some plugins to display it with proper formatting. However, things will be different if you are stuck to a terminal or want to do it in your shell script.
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 into details about using jq command line tool here.
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
You may also tempt to use the cat command but I believe it is 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
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
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
I know there are other ways to parse JSON file and print it in a proper format. You may explore them on your own but these two are sufficient to do the job, which is to pretty print JSON files.