是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
你也可以选择使用在线工具。
我发现http://jsonprettyprint.net是最简单和最简单的。
其他回答
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
我提出了这个解决方案: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,则可以使用此功能。
如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。
我正在使用httpie
$ pip install httpie
你可以这样使用
$ http PUT localhost:8001/api/v1/ports/my
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 93
Content-Type: application/json
Date: Fri, 06 Mar 2015 02:46:41 GMT
Server: nginx/1.4.6 (Ubuntu)
X-Powered-By: HHVM/3.5.1
{
"data": [],
"message": "Failed to manage ports in 'my'. Request body is empty",
"success": false
}
我写了一个工具,它有一个最好的“智能空白”格式器。与这里的大多数其他选项相比,它生成的输出可读性更高,详细程度更低。
下划线cli
这就是“智能空白”的样子:
我可能有点偏见,但它是一个很棒的工具,可以从命令行打印和处理JSON数据。它使用起来超级友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001项不同的小任务,如果用其他方式来做,那会令人惊讶地讨厌。
最新用例:Chrome、开发人员控制台、网络选项卡,全部导出为HAR文件,“cat site.HAR |下划线select‘.url’--outmt text|grep mydomain”;现在,我有一个按时间顺序排列的列表,列出了在加载公司网站期间获取的所有URL。
漂亮的打印很容易:
underscore -i data.json print
同样的事情:
cat data.json | underscore print
同样的事情,更明确:
cat data.json | underscore print --outfmt pretty
这个工具是我目前的激情项目,所以如果你有任何功能需求,我很有机会解决它们。
一个用于漂亮json打印的简单bash脚本
json_prety.sh
#/bin/bash
grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
例子:
cat file.json | json_pretty.sh