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

JsonShellCommand Line

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

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

python -m json.tool < 'file_name'

Solution 2 - Json

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 - Json

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"
}

Solution 4 - Json

Colored output using Pygmentize + Python json.tool

Pygmentize is a killer tool. See this. I combine python json.tool with pygmentize

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

For other similar tools and installation instruction see the answer linked above.

Here is a live demo:

demo

Solution 5 - Json

There are a bunch of them. I personally have this alias in my .zshrc

pjson () {
        ~/bin/pjson.py | less -X
}

where pjson.py is

#!/usr/bin/env python

import json
import sys

try:
    input_str = sys.stdin.read()
    print json.dumps(json.loads(input_str), sort_keys = True, indent = 2)
except ValueError,e:
    print "Couldn't decode \n %s \n Error : %s"%(input_str, str(e))
    

Allows me to use that in a command line as a pipe (something like curl http://.... | pjson).

OTOH, Custom code is a liability so there's jq, which to me looks like the gold standard. It's written in C (and is hence portable with no dependencies like Python or Node), does much more than just pretty printing and is fast.

Solution 6 - Json

From a mac OS 10.15 terminal I can use json_pp:

echo '{ "element0" : "lorem", "element1" : "ipsum" }' | json_pp

Solution 7 - Json

You can use jq package which can be installed in all Linux systems. Install the tool using below commands.

# Redhat based systems(Centos)
yum install -y epel-release
yum install -y jq

# Debian based systems
apt install -y jq

Then you will be able to pipe text streams to the jq tool.

echo '{"test":"value", "test2":"value2"}' | jq

Hope this answer will help.

Solution 8 - Json

In the Mac OS, install jq with the command,

$ brew install jq

You can get the pretty print JSON as similar as,

$ curl -X GET http://localhost:8080/api/v1/appointments/1  | jq


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   117    0   117    0     0   8404      0 --:--:-- --:--:-- --:--:--  9000
{
  "craeted_at": "10:24:38",
  "appointment_date": "2019-02-08",
  "name_of_doctor": "Monika",
  "status": true,
  "price": 12.5,
  "id": 1
}

Solution 9 - Json

Shawn's solution but for Python 3:

echo '{"foo": "bar"}' | python3 -m json.tool

Solution 10 - Json

To format your JSON with proper indentation use JSON.stringify

console.log(JSON.stringify(your_object, null, 2)); // prints in b/w

But to make it prettier by adding colors, you can check out my package beautify-json

beautify-json

Example:

const { jsonBeautify } = require('beautify-json')

let your_object = {
    name: 'Nikhil',
    age: 22,
    isMarried: false,
    girlfriends: null,
    interestedIn: [
        'javascript',
        'reactjs',
        'nodejs'
    ]
}

jsonBeautify(your_object) // It will beautify your object with colors and proper indentation and display it on the terminal

Output: Screenshot of the beautified object printed in terminal

Solution 11 - Json

Formatting json as a table from the command line

You can use jtab - a tool written in rust - to print any json data as a table.

For example:

➜ echo '{"foo": "bar"}' | jtab

+-----+
| foo |
+-----+
| bar |
+-----+

It also works with a json array:

➜  echo '[{"id": "1", "name": "Rust"}, {"id": "2", "name": "Jtab"}]' | jtab

+----+------+
| id | name |
+----+------+
| 1  | Rust |
+----+------+
| 2  | Jtab |
+----+------+

Solution 12 - Json

with python (2 and 3):

alias prettify_json="python -c 'import sys ;import json ; print(json.dumps(json.loads(sys.stdin.read()), indent=4))'"

or with ruby:

alias prettify_json="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

you can use:

echo '{"bar": "abc", "foo": "def"}' | prettify_json
curl http://.../file.json | prettify_json

Solution 13 - Json

I always use json_reformat

echo '{"test":"value", "test2":"value2"}' | json_reformat

{
    "test": "value",
    "test2": "value2"
}

Could be installed by apt-get install yajl even under Windows in MobaXTerm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuca DavanzoView Question on Stackoverflow
Solution 1 - JsonShawn VaderView Answer on Stackoverflow
Solution 2 - JsonFoneboneView Answer on Stackoverflow
Solution 3 - JsonNimrod007View Answer on Stackoverflow
Solution 4 - JsonShubham ChaudharyView Answer on Stackoverflow
Solution 5 - JsonNoufal IbrahimView Answer on Stackoverflow
Solution 6 - JsonRobin StewartView Answer on Stackoverflow
Solution 7 - Jsonsrimaln91View Answer on Stackoverflow
Solution 8 - JsonArefeView Answer on Stackoverflow
Solution 9 - JsonDaveView Answer on Stackoverflow
Solution 10 - JsonNikhil KumaranView Answer on Stackoverflow
Solution 11 - JsonLezzar WalidView Answer on Stackoverflow
Solution 12 - JsonFábio A.View Answer on Stackoverflow
Solution 13 - JsonAlexView Answer on Stackoverflow