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

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

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

…变成这样:

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

当前回答

使用Node.js的单线解决方案如下所示:

$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

例如:

$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

其他回答

我提出了这个解决方案:https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65

# this in your bash profile
jsonprettify() {
  curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
#     "prop": true,
#     "key": [
#         1,
#         2
#     ]
# }

不需要安装任何东西,如果您安装了internet连接和cURL,则可以使用此功能。

如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。

brew安装jq命令+|jq(示例:curl localhost:5000/blocks|jq)享受

工具ydump是一个JSON漂亮的打印机:

$ ydump my_data.json
{
  "foo": "lorem",
  "bar": "ipsum"
}

或者可以通过管道输入JSON:

$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
  "foo": "lorem",
  "bar": "ipsum"
}

这可能是除了使用jq工具之外最短的解决方案。

该工具是OCaml的yojson库的一部分,并在此处进行了说明。

在Debian及其衍生产品上,libyojson-ocml-dev包包含此工具。或者,可以通过OPAM安装yojson。

JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

脚本下载:gist.gitub.com/3738968

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

例子:

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