Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

json - 如何在Shell脚本中漂亮地打印JSON?(How can I pretty-print JSON in a shell script?)

Is there a (Unix) shell script to format JSON in human-readable form?

(是否有(Unix)Shell脚本以易于理解的格式格式化JSON?)

Basically, I want it to transform the following:

(基本上,我希望它可以转换以下内容:)

{ "foo": "lorem", "bar": "ipsum" }

... into something like this:

(...变成这样:)

{
    "foo": "lorem",
    "bar": "ipsum"
}
  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With Python 2.6+ you can just do:

(使用Python 2.6+,您可以执行以下操作:)

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

or, if the JSON is in a file, you can do:

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

python -m json.tool my_json.json

if the JSON is from an internet source such as an API, you can use

(如果JSON来自互联网来源(例如API),则可以使用)

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
}

for all the above cases.

(对于上述所有情况。)

You can put this in .bashrc and it will be available every time in shell.

(您可以将其放在.bashrc并且每次在Shell中都可用。)

Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}' .

(像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'一样调用它。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...