是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
我提出了这个解决方案: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 '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:
sudo apt-get install libjson-xs-perl
它显然也可以在CPAN上使用。
要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
或者:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
要格式化文件中包含的JSON,可以执行以下操作:
$ json_xs < file-full-of.json
要重新格式化为YAML,有些人认为它比JSON更具可读性:
$ json_xs -t yaml < file-full-of.json
根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:
autocmd FileType json setlocal equalprg=json_reformat
对于Node.js,您也可以使用“util”模块。它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。
cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"
yq可以用于漂亮地打印JSON
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json
它有一个定义缩进的选项
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --indent 3
您可以选择彩色和单色输出
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --colors
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --no-colors