如何在shell脚本中漂亮地打印JSON?

是否有(Unix)shell脚本以人类可读的形式格式化JSON

基本上,我希望它能改变以下内容:

{quo;foo&quo;:“lorem",“bar":“ipsum”}

。。。变成这样:

{
&“foo”:“lorem”;,
&“条形图”:“同侧图”;
}

使用Python 2.6+可以执行以下操作:

echo'{quo;foo&quo;:“lorem",“bar":“ipsum&quot}'”python-m json.tool

或者,如果JSON在文件中,您可以执行以下操作:

python-m json.tool my_json.json

如果JSON来自internet源(如API),则可以使用

curlhttp://my_url/ |python-mjson.tool

为方便起见,在所有这些情况下,您都可以使用别名:

别名prettyjson='python-m json.tool'

为了更加方便,只需多输入一点即可:

prettyjson\u s(){
echo-python-mjson.tool
}
prettyjson_f(){
python-mjson.tool“1美元”;
}
prettyjson_w(){
curl-python-mjson.tool
}

对于上述所有情况。您可以将它放在.bashrc中,它将在shell中每次都可用。像prettyjson'{quo;foo&quo;:“lorem",“bar":“ipsum"}一样调用它。

请注意,正如@pnd在下面的注释中指出的,在Python 3.5+中,JSON对象在默认情况下不再排序。要排序,请在末尾添加--sort key标志。即。|python-mjson.tool——排序键

发表评论