在shell脚本中美化打印JSON的方法
技术背景
在shell脚本开发过程中,经常会遇到处理JSON数据的情况。原始的JSON数据通常是紧凑的、难以阅读的,为了方便调试和查看,需要将其以一种更易读的格式进行输出,也就是美化打印JSON。
实现步骤
- 直接从字符串美化打印
1
| echo '{ "foo": "lorem", "bar": "ipsum" }' | python -m json.tool
|
- 从文件中读取JSON并美化打印
1
| python -m json.tool my_json.json
|
- 从网络API获取JSON并美化打印
1
| curl http://my_url/ | python -m json.tool
|
- 设置别名方便使用
1
| alias prettyjson='python -m json.tool'
|
- 定义函数方便使用
1 2 3 4 5 6 7 8 9 10 11
| prettyjson_s() { echo "$1" | python -m json.tool }
prettyjson_f() { python -m json.tool "$1" }
prettyjson_w() { curl "$1" | python -m json.tool }
|
可以将这些函数添加到.bashrc
文件中,以便每次启动shell时都可以使用。
使用jq
工具
- 安装
jq
(如果未安装)1 2
| sudo apt-get update sudo apt-get install jq
|
- 美化打印JSON
1
| echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
|
使用JavaScript和Node.js
- 在命令行指定JSON字符串并美化打印
1
| node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" '{ "foo": "lorem", "bar": "ipsum" }'
|
- 从文件中读取JSON并美化打印
1
| node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync(process.argv[1])), null, 4));" filename.json
|
- 使用管道美化打印
1
| echo '{ "foo": "lorem", "bar": "ipsum" }' | node -e 's=process.openStdin();d=[];s.on("data",function(c){d.push(c);});s.on("end",function(){console.log(JSON.stringify(JSON.parse(d.join("")),null,2));});'
|
使用Perl
- 使用
JSON::XS
模块- 验证JSON文件
1
| json_xs -t null < myfile.json
|
- 美化JSON文件
1
| < src.json json_xs > pretty.json
|
- 如果没有
json_xs
,可以尝试使用json_pp
。
- 使用Perl脚本美化打印
1
| cat json.txt | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), {pretty=>1})'
|
使用Ruby
1
| echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
|
使用underscore-cli
工具
1
| underscore -i data.json print
|
使用pjson
工具
- 安装
pjson
- 美化打印JSON
1
| echo '{ "foo": "lorem", "bar": "ipsum" }' | pjson
|
使用jshon
工具
1
| echo $COMPACTED_JSON_TEXT | jshon
|
核心代码
Python脚本美化打印JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| """ Convert JSON data to human-readable form.
(Reads from stdin and writes to stdout) """
import sys try: import simplejson as json except: import json
print json.dumps(json.loads(sys.stdin.read()), indent=4) sys.exit(0)
|
定义shell函数美化打印JSON
1 2 3
| json_format(){ python3 -c'import fileinput, json; print(json.dumps(json.loads("".join(fileinput.input())), sort_keys=True, indent=4, ensure_ascii=False))' }
|
最佳实践
- 对于简单的JSON美化打印,优先使用
jq
工具,它简单易用,且能处理大型JSON结构。 - 如果已经安装了Python,使用
json.tool
模块也是一个不错的选择,特别是在需要对JSON进行排序或处理非ASCII字符时。 - 对于JavaScript开发者,使用Node.js进行JSON美化打印可以保持代码的一致性。
常见问题
- Python 3.5+中JSON对象默认不排序:可以在使用
json.tool
时添加--sort-keys
参数进行排序。 - Python处理非ASCII字符时被转义:可以使用
--no-ensure-ascii
参数(Python 3.9+)或在代码中设置ensure_ascii=False
来禁用非ASCII字符的转义。