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

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

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

…变成这样:

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

当前回答

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

jj -p # for reading from STDIN

or

jj -p -i input.json

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

其他回答

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

jj -p # for reading from STDIN

or

jj -p -i input.json

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

$ 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"
}

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

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

如果使用npm和Node.js,则可以执行npm install-g json,然后通过json发送命令。执行json-h以获取所有选项。它还可以拉出特定字段,并用-i为输出着色。

curl -s http://search.twitter.com/search.json?q=node.js | json

TL;DR:对于性能,请使用jj-p<my.json。

基准

我在这里采取了一些解决方案,并用下一个虚拟脚本对它们进行了基准测试:

function bench {
    time (
      for i in {1..1000}; do
        echo '{ "foo" : { "bar": { "dolorem" : "ipsum", "quia" : { "dolor" : "sit"} } } }' \
        | $@ > /dev/null
      done
    )
}

这是我的mac(32 GB,苹果M1 Max,YMMV)上的结果:

bench python -m json.tool
# 8.39s user 12.31s system 42% cpu 48.536 total
bench jq
# 13.12s user 1.28s system 87% cpu 16.535 total
bench bat -p -l json # NOTE: only syntax colorisation.
# 1.87s user 1.47s system 66% cpu 5.024 total
bench jj -p
# 1.94s user 2.44s system 57% cpu 7.591 total
bench xidel -s - -e '$json' --printed-json-format=pretty                      
# 4.32s user 1.89s system 76% cpu 8.101 total

感谢@peak和您对jj发现的回答!