是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
尝试pjson。它有颜色!
使用pip安装:
⚡ pip安装pjson
然后将任何JSON内容通过管道传输到pjson。
其他回答
您可以使用Pretier来执行此操作。
npx更漂亮的<JSON文件>应该在给定文件中打印一个经过修饰的JSON版本,而npx更美丽的--write<JSON文件>将用经过修饰的JSON覆盖给定的JSON文件。
对于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的“扩展系统”)。
你只需要使用jq如果未安装jq,则需要先安装jq。
sudo apt-get update
sudo apt-get install jq
安装jq后,只需使用jq
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
输出看起来像
{
"foo": "lorem",
"bar": "ipsum"
}
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
该方法还“检测HTTP响应/标头,打印它们,并跳过主体(用于'curl-i')”。
我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:
sudo apt-get install libjson-xs-perl
它显然也可以在CPAN上使用。
要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
或者:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
要格式化文件中包含的JSON,可以执行以下操作:
$ json_xs < file-full-of.json
要重新格式化为YAML,有些人认为它比JSON更具可读性:
$ json_xs -t yaml < file-full-of.json