是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
下面是如何使用Groovy脚本实现这一点。
创建一个Groovy脚本,让我们说“漂亮的打印”
#!/usr/bin/env groovy
import groovy.json.JsonOutput
System.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }
使脚本可执行:
chmod +x pretty-print
现在从命令行开始,
echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print
其他回答
我提出了这个解决方案: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,则可以使用此功能。
如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。
有TidyJSON。
它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。
我正在使用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
}
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
只需将输出通过管道发送到jq。。
例子:
twurl -H ads-api.twitter.com '.......' | jq .