jsonpath模块
一、使用场景
jsonpath模块可以按照key对python字典进行批量数据读取,而不是使用下表进行读取
二、使用方法
1、语法规则
JSONPath | 描述 |
---|---|
$ | 表示根元素 |
@ | 当前元素 |
. or [] | 子元素 |
… | 不管位置,选择符合条件的元素 |
* | 匹配所有元素节点 |
[] | 迭代器标示,可以在里面做简单的迭代操作,如数组下标、根据内容选值等。 |
[,] | 支持迭代器做多选 |
?() | 支持过滤操作 |
() | 支持表达式计算 |
2、语法示例
jsonpath在线测试网址:http://www.e123456.com/aaaphp/online/jsonpath/
book_dict = {
"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
}
}
}
JSONPath | 描述 |
---|---|
$.store.book[*].author | 获取store中所有的book的作者 |
$…author | 获取所有的作者 |
$.store.* | 获取store下的所有的元素 |
$.store.book[*].price | 获取store中的所有的book的价格 |
$.store.book[2] | 获取第三本书 |
$.store.book[-1:] | 获取最后一本书 |
$.store.book[0,1] | 获取前两本书 |
$.store.book[?(@.isbn)] | 获取有isbn的所有书 |
$.store.book[?(@.price>10)] | 获取价格大于10的所有图书 |
$…* | 获取所有的数据 |
三、在python中的使用
1、jsonpath模块的安装
pip install jsonpath
# 或
pip install jsonpath -i https://pypi.tuna.tsinghua.edu.cn/simple
2、jsonpath提取数据的方法
from jsonpath import jsonpath
# ret是提取结果
ret = jsonpath(json_dict, 'json格式字符串')
四、理解
- jsonpath的作用是转换多重字典嵌套,使用符合其规则的语法可以获得的数据,更加的方便
- 在转换前文件是字符串型的话需要用到request返回的对象(一般是response含有的 response.json() )的方法将字符串数据转换成字典型,再通过 jsonpath 语句提取数据