是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
其他回答
$ sudo apt-get install edit-json
$ prettify_json myfile.json
使用Node.js的单线解决方案如下所示:
$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
例如:
$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
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发现的回答!
一个用于漂亮json打印的简单bash脚本
json_prety.sh
#/bin/bash
grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
例子:
cat file.json | json_pretty.sh
bat是一个cat克隆,语法突出显示:
例子:
echo '{"bignum":1e1000}' | bat -p -l json
-p将不带头输出,-l将显式指定语言。
它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?