是否有(Unix)shell脚本将JSON格式化为可读格式?

基本上,我希望它转换以下内容:

{ "foo": "lorem", "bar": "ipsum" }

…变成这样:

{
    "foo": "lorem",
    "bar": "ipsum"
}

当前回答

有TidyJSON。

它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。

其他回答

你也可以选择使用在线工具。

我发现http://jsonprettyprint.net是最简单和最简单的。

或者,使用Ruby:

echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

我建议使用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

您可以使用此简单命令来实现以下结果:

echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool

使

我将Python的json工具与pygmentize相结合:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

我的回答中列出了一些pygmentize的替代方案。

这里是一个现场演示: