是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使用Node.js的单线解决方案如下所示:
$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
例如:
$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
其他回答
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:
autocmd FileType json setlocal equalprg=json_reformat
我建议使用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 liner的作者。这是一个命令行工具,用于将JSON转换为grep友好格式。试试看。
$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz
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