Python的jsonpath库使用方法实例
作者:shines_m
这篇文章主要介绍了Python的jsonpath库使用方法实例,接口返回的jsonn数据,需要取值后断言,一般我们是使用jsonpath来提取接口返回的数据 ,JsonPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,,需要的朋友可以参考下
一、简介
接口返回的json数据,需要取值后断言,一般我们是使用jsonpath来提取接口返回的数据
JsonPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具。
JsonPath相当于是Xpath 。
安装
pip install jsonpath
二、语法说明
JsonPath解析的内容必须是字典格式,通过JsonPath获得的内容,会以list的形式进行返回 。
如果表达式出现错误,则会返回False(布尔类型的值)
jsonpath表达式的基本格式规范:
| 符号 | 描述 |
| $ | 表示根节点,也是所有jsonpath表达式的开始 |
| . | 表示获取子节点 |
| .. | 表示获取所有符合条件的内容 |
| * | 代表所有的元素节点 |
| [] | 表示迭代器的标示(可以用于处理下标等情况) |
| [,] | 表示多个结果的选择 |
| ?() | 表示过滤操作 |
| @ | 表示当前节点 |
三、代码示例
import jsonpath
data = { "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
}
}
}
# 获取所有book的价格
price = jsonpath.jsonpath(data, '$.store.book[*].price')
print(price)
>> [8.95, 12.99, 8.99, 22.99]
# 获取部分book节点下的price节点值,可支持切片操作
res1 = jsonpath.jsonpath(data, '$.store.book[0,1].price')
res2 = jsonpath.jsonpath(data, '$.store.book[0:2].price')
print(res1)
print(res2)
>> [8.95, 12.99]
>> [8.95, 12.99]
# 获取最后一本书的价格(不能通过[-1]这种方式获取)
res3 = jsonpath.jsonpath(data, '$.store.book[-1:].price')
print(res3)
>> [22.99]
# 获取store节点下所有price节点的值
res4 = jsonpath.jsonpath(data, '$.store...price')
res5 = jsonpath.jsonpath(data, '$..price')
print(res4)
print(res5)
>> [8.95, 12.99, 8.99, 22.99, 19.95]
>> [8.95, 12.99, 8.99, 22.99, 19.95]
# jsonpath解析错误,返回bool类型数据false
res6 = jsonpath.jsonpath(data, '$.store.book111')
print(res6)
>> False
# 获取价格大于10的所有书籍信息
book = jsonpath.jsonpath(data, '$..book[?(@.price>10)]')
print(book)
>> [{'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99}, {'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
# 获取book的价格大于10的prcice
price = jsonpath.jsonpath(data, '$..book[?(@.price>10)].price')
print(price)
>> [12.99, 22.99]
# 过滤所有带有 isbn编号的书籍信息
isbn = jsonpath.jsonpath(data, '$..book[?(@.isbn)]')
print(isbn)
>> [{'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}]到此这篇关于Python的jsonpath库使用方法实例的文章就介绍到这了,更多相关Python的jsonpath库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
