格式化输出 json

 

在命令行或脚本中格式化打印 Json 数据,提高数据可读性。

How can I pretty-print JSON in a shell script?

使用 python 格式化输出

# 字符串
echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

# 文件
python -m json.tool response.json

使用 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.

jq is written in portable C, and it has zero runtime dependencies. You can download a single binary, scp it to a far away machine of the same type, and expect it to work.

# 字符串
echo '{"foo": "lorem", "bar": "ipsum"}' | jq .

jq . <<< '{ "foo": "lorem", "bar": "ipsum" }'

# 文件
jq . response.json

jq --color-output . response.json | less -R

. is a identity filter that takes its input and produces it unchanged as output. Refer to Basic filters for more details.