How can I pretty-print a JSON file from the command line?

I've a file with a sequence of JSON element:

{ element0: "lorem", value0: "ipsum" }
{ element1: "lorem", value0: "ipsum" }
...
{ elementN: "lorem", value0: "ipsum" }

Is there a shell script to format JSON to display file content in a readable form?

I've seen this post, and I think is a good starting point!

My idea is to iterate rows in the file and then:

while read row; do echo ${row} | python -mjson.tool; done < "file_name"

Does anyone have any other ideas?


Solution 1:

Pipe the results from the file into the python json tool 2.6 onwards

python -m json.tool < 'file_name'

Solution 2:

jq - a lightweight and flexible command-line JSON processor

I felt this deserved its own entry when it took me longer than it should have to discover. I was looking for a simple way to pretty-print the json output of docker inspect -f. It was mentioned briefly above by Noufal Ibrahim as part of another answer.

From the jq website (https://stedolan.github.io/jq/):

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

It provides colored output by default and you simply have to pipe to jq, e.g.

jq . < file

Example:

"Raw" json output vs the same piped to jq

Solution 3:

You can use Python JSON tool (requires Python 2.6+).

For example:

echo '{ "element0" : "lorem", "element1" : "ipsum" }' | python -m json.tool

Which will give you:

{
    "element0": "lorem",
    "element1": "ipsum"
}