在Unix Shell脚本中以可读JSON格式显示curl输出

Display curl output in readable JSON format in Unix shell script

在我的Unix Shell脚本中,当我执行curl命令时,结果将显示如下,我将其重定向到文件:

1
{"type":"Show","id":"123","title":"name","description":"Funny","channelTitle":"ifood.tv","lastUpdateTimestamp":"2014-04-20T20:34:59","numOfVideos":"15"}

但是,我希望此输出以可读的JSON格式放入文件中,如下所示:

1
2
3
4
5
6
7
{"type":"Show",
"id":"123",
"title":"name",
"description":"Funny",
"channelTitle":"ifood.tv",
"lastUpdateTimestamp":"2014-04-20T20:34:59",
"numOfVideos":"15"}

如何以这种方式格式化输出?


尝试这样做:

1
curl ... | json_pp

或与jq使用身份过滤器:

1
curl ... | jq '.'

enter image description here

或与nodejs和bash:

1
curl ... | node <<<"var o = $(cat); console.log(JSON.stringify(o, null, 4));"

检查https://stedolan.github.io/jq/


  • brew install jq
  • command + | jq
  • (例如:curl localhost:5000/blocks | jq .)
  • 请享用!
  • enter image description here


    我猜想您要美化JSON输出。
    可以使用python实现:

    curl http://localhost:8880/test.json | python -mjson.tool > out.json


    1
    2
    python -m json.tool
    Curl http://127.0.0.1:5000/people/api.json | python -m json.tool

    也可以提供帮助。


    我发现json_reformat非常方便。所以我只是做了以下事情:

    1
    curl http://127.0.0.1:5000/people/api.json | json_reformat

    而已!


    看看curljson

    1
    2
    $ pip install curljson
    $ curljson -i <the-json-api-url>


    这是吉尔斯答案的补充。有很多方法可以做到这一点,但我个人更喜欢在常见的* nix系统上轻巧,易于记忆且通用的东西(例如,带有您喜欢的Linux风格的标准LTS安装或易于安装)。

    以下是按其优先顺序排列的选项:

  • Python Json.tool模块,例如,
    回声'{" foo":" lorem"," bar":" ipsum"}'| python -mjson.tool
    (优点:几乎到处都有;缺点:没有颜色编码)

  • jq(可能需要安装一次)
    回声'{" foo":" lorem"," bar":" ipsum"}'| q
    (缺点:需要安装jq;优点:颜色编码和通用性)

  • json_pp(在Ubuntu 16.04 LTS中可用),例如
    回声'{" foo":" lorem"," bar":" ipsum"}'| json_pp

  • 对于Ruby用户,
    gem install jsonpretty
    回声'{" foo":" lorem"," bar":" ipsum"}'| jsonpretty


  • 您可以使用此节点模块

    [sudo] npm i -g json; //建议不要使用root特权来安装节点模块

    然后只需在卷曲后附加|json
    curl http://localhost:8880/test.json |json