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

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

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

…变成这样:

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

当前回答

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

例子:

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

其他回答

PHP版本,如果您有PHP>=5.4。

alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json

此外,请务必查看JSONFUI:一个支持折叠的命令行JSON查看器

在一行中使用Ruby:

echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"

您可以为此设置别名:

alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

然后你可以更方便地使用它

echo '{"test":1,"test2":2}' | to_j

{
  "test": 1,
  "test2": 2
}

如果你想用颜色显示JSON,你可以安装awesome_print,

gem install awesome_print

then

alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""

试试看!

echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j

尝试pjson。它有颜色!

使用pip安装:

⚡ pip安装pjson

然后将任何JSON内容通过管道传输到pjson。

使

我将Python的json工具与pygmentize相结合:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

我的回答中列出了一些pygmentize的替代方案。

这里是一个现场演示: