在我的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: Linux系统中用于JSON解码/编码的命令实用程序
echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
"id" : "1",
"title" : "Foo",
"type" : "Bar"
}
您可能希望保持-json_opt漂亮的规范参数,以实现可预测的排序。
jq:轻量级灵活的命令行JSON处理器。它是用可移植的C语言编写的,并且它没有运行时依赖性。
echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
最简单的jq程序是表达式.,它接受输入并将其作为输出而不加修改。
有关其他jq选项,请参阅手册
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"
}