是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
在一行中使用Ruby:
echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"
您可以为此设置别名:
alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""
然后你可以更方便地使用它
echo '{"test":1,"test2":2}' | to_j
{
"test": 1,
"test2": 2
}
如果你想用颜色显示JSON,你可以安装awesome_print,
gem install awesome_print
then
alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""
试试看!
echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j
其他回答
有TidyJSON。
它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。
你也可以选择使用在线工具。
我发现http://jsonprettyprint.net是最简单和最简单的。
一个用于漂亮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
根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:
autocmd FileType json setlocal equalprg=json_reformat
如果您想在控制台可视化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
输出: