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

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

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

…变成这样:

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

当前回答

$ echo '{ "foo": "lorem", "bar": "ipsum" }' \
> | python -c'import fileinput, json;
> print(json.dumps(json.loads("".join(fileinput.input())),
>                  sort_keys=True, indent=4))'
{
    "bar": "ipsum",
    "foo": "lorem"
}

注意:不是这样做的。

在Perl中也是如此:

$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), 
>                                     {pretty=>1})'
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

注2:如果你跑步

echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print(json.dumps(json.loads("".join(fileinput.input())),
                 sort_keys=True, indent=4))'

可读性很好的单词将被编码

{
    "D\u00fcsseldorf": "lorem", 
    "bar": "ipsum"
}

如果您的管道的其余部分将优雅地处理unicode,并且您希望JSON也是人性化的,那么只需使用ensure_ascii=False

echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print json.dumps(json.loads("".join(fileinput.input())),
                 sort_keys=True, indent=4, ensure_ascii=False)'

你会得到:

{
    "Düsseldorf": "lorem", 
    "bar": "ipsum"
}

其他回答

我写了一个工具,它有一个最好的“智能空白”格式器。与这里的大多数其他选项相比,它生成的输出可读性更高,详细程度更低。

下划线cli

这就是“智能空白”的样子:

我可能有点偏见,但它是一个很棒的工具,可以从命令行打印和处理JSON数据。它使用起来超级友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001项不同的小任务,如果用其他方式来做,那会令人惊讶地讨厌。

最新用例:Chrome、开发人员控制台、网络选项卡,全部导出为HAR文件,“cat site.HAR |下划线select‘.url’--outmt text|grep mydomain”;现在,我有一个按时间顺序排列的列表,列出了在加载公司网站期间获取的所有URL。

漂亮的打印很容易:

underscore -i data.json print

同样的事情:

cat data.json | underscore print

同样的事情,更明确:

cat data.json | underscore print --outfmt pretty

这个工具是我目前的激情项目,所以如果你有任何功能需求,我很有机会解决它们。

同意jq。您可以将以下函数添加到$HOME/.bashrc中:

jqless () {
  args=$1
  shift
  jq --color-output . $args "$@" | less --raw-control-chars
}

这允许任意数量的输入JSON文件。

一个用于漂亮json打印的简单bash脚本

json_prety.sh

#/bin/bash

grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'

例子:

cat file.json | json_pretty.sh

下面是Groovy的一行代码:

echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'

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