在我的 Unix shell 脚本中,当我执行 curl 命令时,结果将显示如下,我正在重定向到文件:
{"type":"Show","id":"123","title":"name","description":"Funny","channelTitle":"ifood.tv","lastUpdateTimestamp":"2014-04-20T20:34:59","numOfVideos":"15"}
但是,我希望此输出以可读的 JSON 格式放入文件中,如下所示:
{"type":"Show",
"id":"123",
"title":"name",
"description":"Funny",
"channelTitle":"ifood.tv",
"lastUpdateTimestamp":"2014-04-20T20:34:59",
"numOfVideos":"15"}
如何以这种方式格式化输出?
最佳答案
一些解决方案可供选择:
json_pp: command utility available in Linux systems for JSON decoding/encoding
echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
"id" : "1",
"title" : "Foo",
"type" : "Bar"
}
您可能希望保持 -json_opt 漂亮、规范
参数以实现可预测的排序。
jq: lightweight and flexible command-line JSON processor. It is written in portable C, and it has zero runtime dependencies.
echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
最简单的jq
程序是表达式.
,它接受输入并将其原样作为输出产生。
对于附加 jq
选项检查 the manual
与 python :
echo '{"type":"Bar","id":"1","title":"Foo"}' | python -m json.tool
{
"id": "1",
"title": "Foo",
"type": "Bar"
}
与 nodejs和 bash :
echo '{"type":"Bar","id":"1","title":"Foo"}' | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
https://stackoverflow.com/questions/27238411/