是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
我知道最初的帖子要求提供一个shell脚本,但有太多有用和不相关的答案,可能对原作者没有帮助。添加到不相关的内容:)
顺便说一下,我无法使用任何命令行工具。
如果有人想要简单的JSON JavaScript代码,他们可以这样做:
JSON.stringfy(JSON.parse(str), null, 4)
http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos
这里是JavaScript代码,它不仅美化了JSON,还按其属性或属性和级别对其进行排序。
如果输入是
{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1},
它要么打印(将所有对象分组在一起):
{
"b": 1,
"c": 1,
"a": {
"a1": 1,
"b1": 2
}
}
OR(仅按键排序):
{
"a": {
"a1": 1,
"b1": 2
},
"b": 1,
"c": 1
}
其他回答
看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。
gem install jazor
jazor --help
根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:
autocmd FileType json setlocal equalprg=json_reformat
我提出了这个解决方案: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,则可以使用此功能。
如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。
在一行中使用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
同意jq。您可以将以下函数添加到$HOME/.bashrc中:
jqless () {
args=$1
shift
jq --color-output . $args "$@" | less --raw-control-chars
}
这允许任意数量的输入JSON文件。