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

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

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

…变成这样:

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

当前回答

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

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

其他回答

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

$ sudo apt-get install edit-json
$ prettify_json myfile.json

我使用JSON.stringify的“space”参数在JavaScript中漂亮地打印JSON。

示例:

// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);

// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');

在带有Node.js的Unix命令行中,在命令行中指定JSON:

$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
  '{"foo":"lorem","bar":"ipsum"}'

退货:

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

从带有Node.js的Unix命令行,指定包含JSON的文件名,并使用四个空格的缩进:

$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
      .readFileSync(process.argv[1])), null, 4));"  filename.json

使用管道:

echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
 s=process.openStdin();\
 d=[];\
 s.on('data',function(c){\
   d.push(c);\
 });\
 s.on('end',function(){\
   console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
 });\
"

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

下划线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

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

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

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