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

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

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

…变成这样:

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

当前回答

J.F.Sebastian的解决方案在Ubuntu 8.04中不适用。下面是一个经过修改的Perl版本,可以与旧的1.X JSON库一起使用:

perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'

其他回答

$ sudo apt-get install edit-json
$ prettify_json myfile.json

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

下面是如何使用Groovy脚本实现这一点。

创建一个Groovy脚本,让我们说“漂亮的打印”

#!/usr/bin/env groovy

import groovy.json.JsonOutput

System.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }

使脚本可执行:

chmod +x pretty-print

现在从命令行开始,

echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print

在一行中使用Ruby:

echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"

您可以为此设置别名:

alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

然后你可以更方便地使用它

echo '{"test":1,"test2":2}' | to_j

{
  "test": 1,
  "test2": 2
}

如果你想用颜色显示JSON,你可以安装awesome_print,

gem install awesome_print

then

alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""

试试看!

echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j

brew安装jq命令+|jq(示例:curl localhost:5000/blocks|jq)享受