jsonpath
1、json包
首先有必要知晓json包常用的两个方法
| json.dumps() | 将python对象(字典)编码成Json字符串 |
| json.loads() | 将Json字符串解码成python对象(字典) |
2、jsonpath介绍
JsonPath是一种简单的方法来提取给定JSON文档的部分内容。 JsonPath支持许多编程语言,如Javascript,Python,Java等。
JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。
安装:pip install jsonpath==0.82
使用场景:
1、从响应结果提取接口数据,用于其他接口
2、只能处理json格式的数据(字典)
3、jsonpath原字符

4、实际使用讲解
from jsonpath import jsonpath
dic = {
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"isbn": "0-395-19395-1",
"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
}
},
"expensive": 10
}
1、获取expensive
res = jsonpath(dic, '$.expensive')或者res = jsonpath(dic, '$[expensive]')或者res = jsonpath(dic, '$..expensive')
2、获取bicycle
res = jsonpath(dic, '$.store.bicycle')或者res = jsonpath(dic, '$..bicycle')
3、获取第一个book的author
res = jsonpath(dic, '$.store.book[0].author')或者res = jsonpath(dic, '$..book[0].author')
4、获取第2~4个book的price
res = jsonpath(dic, '$.store.book[1:4].price')或者res = jsonpath(dic, '$..book[1:4].price')
5、获取第2个和第4个book的price
res = jsonpath(dic, '$.store.book[1,3].price')或者res = jsonpath(dic, '$..book[1,3].price')
6、获取《Moby Dick》这本书的信息
res = jsonpath(dic, "$..book.[?(@.title=='Moby Dick')]")
7、获取price小于9且category为fiction的book信息
res = jsonpath(dic, "$..book.[?(@.price<9 && @.category=='fiction')]")
8、获取author为Nigel Rees或J. R. R. Tolkien的book的isbn
res = jsonpath(dic, "$..book.[?(@.author in ['Nigel Rees', 'J. R. R. Tolkien'])].isbn")
需要注意的是:返回的结果res是列表list格式的

浙公网安备 33010602011771号