是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
一个用于漂亮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
其他回答
对于Perl,使用CPAN模块JSON::XS。它安装一个命令行工具json_xs。
验证:
json_xs -t null < myfile.json
将JSON文件src.JSON前置为pretty.JSON:
< src.json json_xs > pretty.json
如果没有json_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。
当您的系统上安装了节点时,以下工作正常。
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
bat是一个cat克隆,语法突出显示:
例子:
echo '{"bignum":1e1000}' | bat -p -l json
-p将不带头输出,-l将显式指定语言。
它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
只需将输出通过管道发送到jq。。
例子:
twurl -H ads-api.twitter.com '.......' | jq .