jq
说明
curl命令使用jq,结合jsopath,可以对响应的json数据做格式化和过滤处理 最简单的jq程序是表达式 ‘.’ ,表示响应的数据 更多信息,查看官方文档https://stedolan.github.io/jq/
示例
1.不使用jq时的响应结果
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5'

2.使用jq格式化响应结果
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'

3.获取响应列表中的第一个对象
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0]'
4.获取响应列表中的第一个对象中的具体信息,并以json格式显示(匹配信息的路径使用jsonpath)
jq '.[0] | {message: .commit.message, name: .commit.committer.name}'

JsonPath
| DSL | |
|---|---|
| xml | xpath |
| html | css selector + xpath |
| text | regex |
| json | jsonpath |
| assertion | hamcrest |
jsonpath语法
| xpath | json | 描述 |
|---|---|---|
| / | . | 根元素 |
| . | @ | 当前对象/元素 |
| / | . 或 [] | 子节点操作符 |
| * | * | 通配符,所有元素和对象 |
| [] | ?[] | 使用过滤条件 |
| // | .. | 选取所有子元素,而不管它们在文档中的位置。 |
更多信息,查看官方文档:https://goessner.net/articles/JsonPath/
示例
下面以book.json为例,体验jsonpath的用法
book.json
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
| XPath | JSONPath | Result |
|---|---|---|
/store/book/author |
$.store.book[*].author |
store中所有book的author |
| //author | $..author |
所有 authors |
/store/* |
$.store.* |
store中的所有东西。包括 books 和red bicycle. |
/store//price |
$.store..price |
store中所有东西的价格 |
//book[3] |
$..book[2] |
第3本书的信息 |
//book[last()] |
$..book[(@.length-1)]$..book[-1:] |
最后一本书的序号 |
//book[position()<3] |
$..book[0,1]$..book[:2] |
the first two books |
//book[isbn] |
$..book[?(@.isbn)] |
筛选有ISBN号的book |
//book[price<10] |
$..book[?(@.price<10)] |
筛选价格小于10的book |
//* |
$..* |
所有元素 |
