在使用Python + requests + pytest +allure 的架構中,jsonpath 起至關重要的作用
簡單的說, jsonpath 是用于提取接口資料響應為json格式的值
舉例說明:
某個接口資料傳回格式如下:
rsp = {
"code": 200,
"data": {
"rows":[
{"name": "a", "sex": "male"},
{"name": "b", "sex": "female"},
{"name": "c", "sex": "male"}
]
},
"query":170085
}
1.取code的值,可以使用絕對路徑或者使用相對路徑
from jsonpath import jsonpath
code1 = jsonpath(rsp, "$.rsp.code")
code2 = jsonpath(rsp, "$..code")
2.取rows下所有的資料
from jsonpath import jsonpath
rowsList = jsonpath(rsp, "$..rows[*]")
3.取rows 下所有的name
from jsonpath import jsonpath
nameList = jsonpath(rsp, "$..rows[*].name")
4.按條件查找,取rows下,name是c的性别字段, 如果有多個條件支援邏輯運算符 【and 、or】等
from jsonpath import jsonpath
sex = jsonpath(rsp, "$..rows[?(@.name=='c')].sex")