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

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

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

…变成这样:

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

当前回答

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

其他回答

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

例子:

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

如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。

curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'

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

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

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

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

我通常只做:

echo '{"test":1,"test2":2}' | python -mjson.tool

要检索选择数据(在本例中为“测试”值):

echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'

如果JSON数据在文件中:

python -mjson.tool filename.json

如果您想使用身份验证令牌在命令行上使用curl一次性完成所有操作:

curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool