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

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

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

…变成这样:

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

当前回答

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

其他回答

或者,使用Ruby:

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

你可以用西德尔。

Xidel是一个命令行工具,可以使用CSS、XPath 3.0、XQuery 3.0、JSONiq或模式模板从HTML/XML页面或JSON API下载和提取数据。它还可以创建新的或转换的XML/HTML/JSON文档。

默认情况下,Xidel漂亮打印:

$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
  "foo": "lorem",
  "bar": "ipsum"
}

or:

$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
  "foo": "lorem",
  "bar": "ipsum"
}

PHP版本,如果您有PHP>=5.4。

alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json

使用以下命令安装yajl工具:

sudo apt-get install yajl-tools

然后

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

我用jshon来做你所描述的事情。只需运行:

echo $COMPACTED_JSON_TEXT | jshon

您还可以传递参数来转换JSON数据。