是否有(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
其他回答
有TidyJSON。
它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。
如果您想在控制台可视化json日志,可以使用munia漂亮的json
npm install -g munia-pretty-json
您的json数据(app-log.json)
{"time":"2021-06-09T02:50:22Z","level":"info","message":"Log for pretty JSON","module":"init","hostip":"192.168.0.138","pid":123}
{"time":"2021-06-09T03:27:43Z","level":"warn","message":"Here is warning message","module":"send-message","hostip":"192.168.0.138","pid":123}
运行命令:
munia-pretty-json app-log.json
下面是控制台上的可读输出:
您可以使用模板格式化输出。默认模板为“{time}{level-c}{{message}”
使用模板:
munia-pretty-json -t '{module -c} - {level} - {message}' app-log.json
输出:
如果使用npm和Node.js,则可以执行npm install-g json,然后通过json发送命令。执行json-h以获取所有选项。它还可以拉出特定字段,并用-i为输出着色。
curl -s http://search.twitter.com/search.json?q=node.js | json
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
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