如何在 shell 脚本中漂亮地打印 JSON? [英] How can I pretty-print JSON in a shell script?
问题描述
是否有(Unix)shell 脚本可以将 JSON 格式化为人类可读的格式?
Is there a (Unix) shell script to format JSON in human-readable form?
基本上,我希望它转换以下内容:
Basically, I want it to transform the following:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
推荐答案
使用 Python 2.6+ 你可以:
With Python 2.6+ you can do:
echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool
或者,如果 JSON 在一个文件中,你可以这样做:
or, if the JSON is in a file, you can do:
python -m json.tool my_json.json
如果 JSON 来自互联网资源,例如 API,您可以使用
if the JSON is from an internet source such as an API, you can use
curl http://my_url/ | python -m json.tool
为了方便所有这些情况,您可以创建别名:
For convenience in all of these cases you can make an alias:
alias prettyjson='python -m json.tool'
<小时>
为了更方便,只需输入更多内容即可准备就绪:
For even more convenience with a bit more typing to get it ready:
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"}'
一样调用它.
for all the above cases. You can put this in .bashrc
and it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
.
请注意,正如@pnd 在下面的评论中指出的那样,在 Python 3.5+ 中,默认情况下不再对 JSON 对象进行排序.要排序,请在末尾添加 --sort-keys
标志.IE.<代码>... |python -m json.tool --sort-keys.
Note that as @pnd pointed out in the comments below, in Python 3.5+ the JSON object is no longer sorted by default. To sort, add the --sort-keys
flag to the end. I.e. ... | python -m json.tool --sort-keys
.
这篇关于如何在 shell 脚本中漂亮地打印 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!