是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
你也可以选择使用在线工具。
我发现http://jsonprettyprint.net是最简单和最简单的。
其他回答
这里有一个比Json的pretify命令更好的Ruby解决方案。gem colorful_json相当不错。
gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
"foo": "lorem",
"bar": "ipsum"
}
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
该方法还“检测HTTP响应/标头,打印它们,并跳过主体(用于'curl-i')”。
TL;DR:对于性能,请使用jj-p<my.json。
基准
我在这里采取了一些解决方案,并用下一个虚拟脚本对它们进行了基准测试:
function bench {
time (
for i in {1..1000}; do
echo '{ "foo" : { "bar": { "dolorem" : "ipsum", "quia" : { "dolor" : "sit"} } } }' \
| $@ > /dev/null
done
)
}
这是我的mac(32 GB,苹果M1 Max,YMMV)上的结果:
bench python -m json.tool
# 8.39s user 12.31s system 42% cpu 48.536 total
bench jq
# 13.12s user 1.28s system 87% cpu 16.535 total
bench bat -p -l json # NOTE: only syntax colorisation.
# 1.87s user 1.47s system 66% cpu 5.024 total
bench jj -p
# 1.94s user 2.44s system 57% cpu 7.591 total
bench xidel -s - -e '$json' --printed-json-format=pretty
# 4.32s user 1.89s system 76% cpu 8.101 total
感谢@peak和您对jj发现的回答!