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

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

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

…变成这样:

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

当前回答

对于Node.js,您也可以使用“util”模块。它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。

cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk =>  {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"

其他回答

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发现的回答!

只需将输出通过管道发送到jq。。

例子:

twurl -H ads-api.twitter.com '.......' | jq .

我是json liner的作者。这是一个命令行工具,用于将JSON转换为grep友好格式。试试看。

$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz

这里有一个比Json的pretify命令更好的Ruby解决方案。gem colorful_json相当不错。

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}

更新我现在使用jq,正如另一个答案中所建议的。它在过滤JSON方面非常强大,但最基本的是,它也是一种漂亮的打印JSON以供查看的绝佳方式。

jsonpp是一个非常好的命令行JSON漂亮的打印机。

从自述文件:

漂亮的打印web服务响应如下:curl-s-L http://<!---->t.co/tYTq5Pu|jsonpp并使磁盘上运行的文件变得漂亮:jsonpp数据/long_malformed.json

如果您使用的是Mac OS X,则可以酝酿安装jsonpp。如果没有,您可以简单地将二进制文件复制到$PATH中的某个位置。