shell解析json工具jq

Home / shell解析json工具jq

shell解析json工具jq

2015-6-15 20:11:17 | Shell | 没有评论

在用curl操作的时候,返回的Content-Type为application/json,输出格式不是嵌套,比较难看,本想全部写在python里处理一下,但一个curl命令四五行,-d里面各种单双引号夹杂,粘贴了之后,要么手动改,要么还要转义,更麻烦,于是乎脑海中闪现了两个字母jq

这玩意是shell里处理json的,当然此刻我的最大目的只是需要美观

debian上直接apt-get进行安装:

sudo apt-get install jq

如果无法直接安装,可以添加下面源:
deb http://ftp.de.debian.org/debian/ wheezy-backports main contrib non-free

 

 

下面是一个比较丑陋的json格式:

~$ cat hi 
{"lihui":{"sex":"male", "age":30, "love":{"book":"lihui_book", "music":"lihui_music" }}, "lilei":"who"}

通过jq直接立马美观,其实还有绿色蓝色区分的

~$ cat hi | jq '.'
{
  "lilei": "who",
  "lihui": {
    "love": {
      "music": "lihui_music",
      "book": "lihui_book"
    },
    "age": 30,
    "sex": "male"
  }
}

想解析具体key的value也是手到擒来

stack@commonqa-devstack:~$ cat hi | jq '.lihui'
{
  "love": {
    "music": "lihui_music",
    "book": "lihui_book"
  },
  "age": 30,
  "sex": "male"
}
stack@commonqa-devstack:~$ cat hi | jq '.lihui.love'
{
  "music": "lihui_music",
  "book": "lihui_book"
}

 

手动检验,测试还是很方便的~!

About Author

发表评论