是否有(Unix)Shell脚本来以人类可读的格式格式化JSON?
基本上,我希望它可以转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
最佳答案
使用Python 2.6+,您可以执行以下操作:
echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool
或者,如果JSON在文件中,则可以执行以下操作:python -m json.tool my_json.json
如果JSON来自互联网来源(例如API),则可以使用curl http://my_url/ | python -m json.tool
为方便起见,在所有这些情况下都可以使用别名:alias prettyjson='python -m json.tool'
为了方便起见,请进行更多输入以使其就绪:
prettyjson_s() {
echo "$1" | python -m json.tool
}
prettyjson_f() {
python -m json.tool "$1"
}
prettyjson_w() {
curl "$1" | python -m json.tool
}
以上所有情况。您可以将其放在.bashrc
中,并且每次在shell中都可用。像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
一样调用它。请注意,正如@pnd在以下注释中指出的那样,在Python 3.5+中,默认情况下不再对JSON对象进行排序。要进行排序,请将
--sort-keys
标志添加到末尾。即... | python -m json.tool --sort-keys
。