shell 中格式化显示 json 字符串

有时需要在终端环境中查看 json 数据,比如使用 curl 调试接口时。直接看到的 json 数据是类似这样的: $ echo ‘{“foo”: “lorem”, “bar”: “ipsum”}’ {“foo”: “lorem”, “bar”: “ipsum”} 如果想要以更直观的方式格式化显示 json 数

有时需要在终端环境中查看 json 数据,比如使用 curl 调试接口时。直接看到的 json 数据是类似这样的:

1
2
$ echo '{"foo": "lorem", "bar": "ipsum"}'
{"foo": "lorem", "bar": "ipsum"}

如果想要以更直观的方式格式化显示 json 数据,可以利用 python3 提供的标准库 json 来实现:

1
2
3
4
5
$ echo '{"foo": "lorem", "bar": "ipsum"}' | python3 -m json.tool
{
"foo": "lorem",
"bar": "ipsum"
}

为了更方便地使用这一工具,可以为它设置一个别名:

将下面内容写入 ~/.bashrc 或其他您的 shell 配置文件中:

1
alias pjson='python3 -m json.tool'

执行 source ~/.bashrc

之后在该 shell 下就可以这样用了:

1
2
3
4
5
$ echo '{"foo": "lorem", "bar": "ipsum"}' | pjson
{
"foo": "lorem",
"bar": "ipsum"
}

参考文献


shell 中格式化显示 json 字符串
https://www.frytea.com/post/20220420181100.html
作者
Tianlun Song
发布于
2022年4月20日
更新于
2024年6月10日
许可协议