学习python自动化——jsonpath
一、安装
pip install jsonpath
二、语法
$ 表示根元素
@ 当前元素
.or[] 子元素
.. 递归搜索(不管当前路径,搜索符合条件的数据)
* 通配符,表示所有的元素
[] 子元素操作符
[,] 支持迭代器中做多选,多个key用逗号隔开
[start: end: step] 数组分割操作,等同于切片
?() 应用过滤表示式
() 脚本表达式,使用在脚本引擎下面
三、写法
import jsonpath
response ={
"teacher":{
"name":"李小二",
"sex":"男",
"age":30,
"height":185.5,
"teacher":"递归搜索测试" },
"class_one":{
"students":[
{
"name":"张一",
"sex":"男",
"age":18,
"height":170.5 },
{
"name":"张二",
"sex":"女",
"age":20,
"height":160.5}]}}
3.1、提取根节点下的字段值,提取出来的是list
3.1.1、$.字段名
res1=jsonpath.jsonpath(response,"$.teacher")
print(res1) #[{'name': '李小二', 'sex': '男', 'age': 30, 'height': 185.5, 'teacher': '递归搜索测试'}]
3.1.2、$[字段名]
res2=jsonpath.jsonpath(response,"$[teacher]")
print(res2) #[{'name': '李小二', 'sex': '男', 'age': 30, 'height': 185.5, 'teacher': '递归搜索测试'}]
3.2、提取指定的值,返回list
3.2.1、$.字段名.字段名
res3=jsonpath.jsonpath(response,"$.teacher.name")
print(res3) #['李小二']
3.2.2、$[字段名][字段名]
res4=jsonpath.jsonpath(response,"$[teacher][name]")
print(res4) #['李小二']
3.3、递归提取,获取能匹配的所有字段,返回list
$..字段名
res5=jsonpath.jsonpath(response,"$..name")
print(res5) #['李小二', '张一', '张二']
3.4、条件筛选
$..[?(@.筛选条件)]
res6=jsonpath.jsonpath(response,"$..[?(@.sex=='女')]")
print(res6) #[{'name': '张二', 'sex': '女', 'age': 20, 'height': 160.5}]