如何从命令行漂亮地打印 JSON 文件?

我有一个带有 JSON 元素序列的文件:

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

是否有一个 shell 脚本来格式化 JSON 以便以可读的形式显示文件内容?

我看过 这个的帖子,我认为这是一个很好的起点!

我的想法是迭代文件中的行,然后:

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

还有人有其他想法吗?

106960 次浏览

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

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.

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

python -m json.tool < 'file_name'

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

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

Shawn's solution but for Python 3:

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

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.

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
}

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

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

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

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

From a mac OS 10.15 terminal I can use json_pp:

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