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

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

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

…变成这样:

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

当前回答

您可以简单地使用jq或json_pp等标准工具。

echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp

or

echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq

将像下面这样美化输出(jq甚至更丰富多彩):

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

jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。

其他回答

jj速度极快,可以经济地处理巨大的JSON文档,不干扰有效的JSON数字,并且易于使用,例如。

jj -p # for reading from STDIN

or

jj -p -i input.json

它(2018)仍然很新,所以它可能不会像您期望的那样处理无效的JSON,但它很容易安装在主要平台上。

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

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

我建议使用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
$ sudo apt-get install edit-json
$ prettify_json myfile.json

工具ydump是一个JSON漂亮的打印机:

$ ydump my_data.json
{
  "foo": "lorem",
  "bar": "ipsum"
}

或者可以通过管道输入JSON:

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

这可能是除了使用jq工具之外最短的解决方案。

该工具是OCaml的yojson库的一部分,并在此处进行了说明。

在Debian及其衍生产品上,libyojson-ocml-dev包包含此工具。或者,可以通过OPAM安装yojson。