我如何在(Unix)shell脚本中漂亮地打印JSON? [英] How can I pretty-print JSON in a (Unix) shell script?

查看:204
本文介绍了我如何在(Unix)shell脚本中漂亮地打印JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个(Unix)shell脚本来以可读的形式格式化JSON?

基本上,我希望它能够转化如下内容:

  {foo:lorem,bar:ipsum} 

...就像这样:

  {
foo:lorem,
bar:ipsum
}




  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 

为了方便起见,您可以使用别名: p>

 别名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}'


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" }

... into something like this:

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

解决方案

With Python 2.6+ you can just do:

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

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

python -m json.tool my_json.json

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
}

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"}'.

这篇关于我如何在(Unix)shell脚本中漂亮地打印JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆