92

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?

3
  • 7
    possible duplicate of How can I pretty-print JSON? Commented Mar 31, 2015 at 23:25
  • 8
    You can just do cat somefile.json | jq . to pretty-print the file (assuming you have jq installed). Commented Oct 19, 2016 at 18:52
  • 2
    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.) Commented Aug 29, 2019 at 12:16

13 Answers 13

156

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

python -m json.tool < 'file_name'
Sign up to request clarification or add additional context in comments.

3 Comments

Do you know how to do this for all files in a directory? I'm not used to bash scripting yet.
add alias ppjson="python -m json.tool" to your ~/.profile file to avoid coming back here next time you need this
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.
87

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

3 Comments

erratum : pipe to jq '.' as jq requires this minimal directive
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)
this is fantastic, downloaded this app and added to my bins folder on my various PCs.
57

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

Comments

18

From a mac OS 10.15 terminal I can use json_pp:

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

1 Comment

Brilliant answer, wish I could upvote more! Did the trick spot on for us.
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

1 Comment

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)
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.

6 Comments

nice even this solution!
The python script is good, but why wrap it in a shell function in the first place?
so the solution is to add a bash script that will run a python script which will only work on your local machine ?
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.
The really valuable thing in the answer is jq though. I think it's superior to all the solutions in this question.
|
6

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
}

Comments

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.

1 Comment

You'll need epel-release for CentOS 7
2

Shawn's solution but for Python 3:

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

Comments

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

1 Comment

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.
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 |
+----+------+

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.