什么是jq
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
安装前在命令行使用的效果
安装后再命令行使用的效果
安装前
最简单的方法是使用homebrew安装,所以先安装homebrew
安装homebrew
- 在命令行中输入安装命令
详见homebrewruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
安装完成后,可使用命令brew doctor 来检查是否安装成功brew doctor
安装jq
- 一键安装
brew install jq
- 若使用brew报错,可卸载homebrew后重新安装
使用
常用方法
- 格式化
curl 'http://xxx.xxx.com/v1/GoodsTag/getAllTagList' -s | jq '.'
- 获取特定字段:.特定字段
curl 'http://xxx.xxx.com/v1/GoodsTag/getAllTagList' -s | jq '.response_status'
以豆瓣api为例子
{
"id":"1220562",
"alt":"http:\/\/book.douban.com\/book\/1220562",
"rating":{"max":10, "average":"7.0", "numRaters":282, "min":0},
"author":[{"name":"片山恭一"}, {"name":"豫人"}],
"alt_title":"",
"image":"http://img3.douban.com\/spic\/s1747553.jpg",
"title":"满月之夜白鲸现",
"mobile_link":"http:\/\/m.douban.com\/book\/subject\/1220562\/",
"summary":"那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。",
"attrs":{
"publisher":["青岛出版社"],
"pubdate":["2005-01-01"],
"author":["片山恭一", "豫人"],
"price":["18.00元"],
"title":["满月之夜白鲸现"],
"binding":["平装(无盘)"],
"translator":["豫人"],
"pages":["180"]
},
"tags":[
{"count":106, "name":"片山恭一"},
{"count":50, "name":"日本"},
{"count":42, "name":"日本文学"},
{"count":30, "name":"满月之夜白鲸现"},
{"count":28, "name":"小说"},
{"count":10, "name":"爱情"},
{"count":7, "name":"純愛"},
{"count":6, "name":"外国文学"}
]
}
-
数组操作
- 获取数组tags中第一个元素count
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.tags[0].count'
-
重新组合
- 将tag数组中的元素count,name 输出为code, mingzi,
|:the output of one filter into the input of another,类似管道符
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.tags[] | {code:.count, mingzi:.name'
- 结果
- 将tag数组中的元素count,name 输出为code, mingzi,
{
"code": 138,
"mingzi": "片山恭一"
}
{
"code": 65,
"mingzi": "日本"
}
{
"code": 61,
"mingzi": "日本文学"
}
{
"code": 38,
"mingzi": "小说"
}
{
"code": 32,
"mingzi": "满月之夜白鲸现"
}
{
"code": 15,
"mingzi": "爱情"
}
{
"code": 8,
"mingzi": "純愛"
}
{
"code": 8,
"mingzi": "外国文学"
}
- 获取多个结果 ,分隔多个结果
- 命令行输入
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.tags[0].count, .tags[0].name'
- 结果:
138
片山恭一
- 长度
- JSON 对象
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.| length'
- JSON 数组
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.tags | length'
- 字符串
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.summary | length'
- keys
curl 'https://api.douban.com/v2/book/1220562' -s | jq '.keys'
[
"alt",
"alt_title",
"author",
"author_intro",
"binding",
"catalog",
"id",
"image",
"images",
"isbn10",
"isbn13",
"origin_title",
"pages",
"price",
"pubdate",
"publisher",
"rating",
"subtitle",
"summary",
"tags",
"title",
"translator",
"url"
]
- map(foo)
echo '[1,5,3]' | jq 'map(.+10)'
[ 11, 15, 13]
- select(foo)
echo '[1,5,3,0,7]' | jq 'map(select(.<2))'
[ 1, 0]