89

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • 7
    possible duplicate of [How can I pretty-print JSON?](http://stackoverflow.com/questions/352098/how-can-i-pretty-print-json) – Hubert Kario Mar 31 '15 at 23:25
  • 7
    You can just do `cat somefile.json | jq .` to pretty-print the file (assuming you have jq installed). – nonbeing Oct 19 '16 at 18:52
  • 1
    It's important to note that the OP *says* "JSON" but actually means Newline-Delimited JSON (NDJSON), with no comma between top level objects. (This is common in JSON-based logging frameworks.) – Coderer Aug 29 '19 at 12:16

13 Answers13

151

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

python -m json.tool < 'file_name'
sds
  • 58,617
  • 29
  • 161
  • 278
Shawn Vader
  • 12,285
  • 11
  • 52
  • 61
  • Do you know how to do this for all files in a directory? I'm not used to bash scripting yet. – keiki Dec 29 '15 at 10:18
  • 7
    add `alias ppjson="python -m json.tool"` to your `~/.profile` file to avoid coming back here next time you need this – jcollum Aug 28 '18 at 18:30
  • This does not work for me !! I get `Expecting property name: line 1 column 3 (char 2)`. Python 2.7.16 on Linux with 4.4.0 kernel, Debian buster with `python` and `python-cjson` packages installed. – BrendanSimon Nov 22 '19 at 03:08
79

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

sds
  • 58,617
  • 29
  • 161
  • 278
Fonebone
  • 895
  • 6
  • 11
  • 5
    erratum : pipe to jq '.' as jq requires this minimal directive – Titou Jan 03 '17 at 13:09
  • `jq` has options to change indentation `--indent 2` and sort the keys in objects `--sort-keys` (which is very useful when checking JSON into a repository because then diffs are much more informative) – Eponymous May 29 '19 at 04:16
55

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"
}
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Nimrod007
  • 9,825
  • 8
  • 48
  • 71
15

From a mac OS 10.15 terminal I can use json_pp:

echo '{ "element0" : "lorem", "element1" : "ipsum" }' | json_pp
Robin Stewart
  • 3,147
  • 20
  • 29
13

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

kenorb
  • 155,785
  • 88
  • 678
  • 743
Shubham Chaudhary
  • 47,722
  • 9
  • 78
  • 80
  • 3
    Nice! I didn't know pygmentize! But I had to install it first, then run command "....| pygmentize -l python", your command "... | pygmentize -g" didn't work for me (pretty print json but uncolered) – Luca Davanzo Nov 06 '15 at 11:37
6

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.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • nice even this solution! – Luca Davanzo Nov 28 '13 at 13:13
  • 3
    The python script is good, but why wrap it in a shell function in the first place? – Jo So Nov 28 '13 at 13:30
  • 2
    so the solution is to add a bash script that will run a python script which will only work on your local machine ? – Nimrod007 Nov 28 '13 at 14:03
  • Jo So: I did that so that the pager would work with `-X`. It's useful to have a pager but by default, `less` clears the screen and things like that which are undesirable. – Noufal Ibrahim Nov 28 '13 at 18:30
  • Nimrod007: Not really. It's just something in my stash of quick and dirty scripts. Works for me so I haven't bothered changing it. I also like the fact that it has a pager. – Noufal Ibrahim Nov 28 '13 at 18:33
  • 4
    The really valuable thing in the answer is `jq` though. I think it's superior to all the solutions in this question. – Noufal Ibrahim Nov 28 '13 at 18:34
5

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.

srimaln91
  • 1,176
  • 10
  • 21
5

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
}
Arefe
  • 11,321
  • 18
  • 114
  • 168
2

Shawn's solution but for Python 3:

echo '{"foo": "bar"}' | python3 -m json.tool
Dave
  • 75
  • 7
1

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 1
    I think the problem with the girlfriends is that you need to extend your interests a bit beyond programming. Have you thought of literature or poetry, or a sport like skydiving? But thanks for the pointer. – Henry Story May 16 '22 at 13:54
1

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 |
+----+------+
Lezzar Walid
  • 148
  • 5
0

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
Fábio A.
  • 31
  • 1
0

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

Alex
  • 1