是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
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
其他回答
我提出了这个解决方案: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,则可以使用此功能。
如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。
bat是一个cat克隆,语法突出显示:
例子:
echo '{"bignum":1e1000}' | bat -p -l json
-p将不带头输出,-l将显式指定语言。
它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?
我通常只做:
echo '{"test":1,"test2":2}' | python -mjson.tool
要检索选择数据(在本例中为“测试”值):
echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'
如果JSON数据在文件中:
python -mjson.tool filename.json
如果您想使用身份验证令牌在命令行上使用curl一次性完成所有操作:
curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
该方法还“检测HTTP响应/标头,打印它们,并跳过主体(用于'curl-i')”。