Jsonpath断言、接口依赖

本文介绍了JsonPath的基础用法,包括路径表达式、条件查询、断言示例以及如何在API接口中应用JsonPath获取和传递数据,展示了如何使用requests库进行HTTP请求并进行数据验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsonpath基础

#格式:$路径
#1. $.key
#2. $..key       多层目录查询
#3. $.key[2]     列表可以通过下标查询
#4. $.key[?(@.key==year)]    根据条件过滤数组元素
#5. $.key[0:2]       查询区间数据

jsonpath断言

url = "http://shop.com/index.php?s=/api/user/login"
#公共参数
public_data = {"application": "app","application_client_type": "weixin"}
#以content-type='application/json'类型传参
data = {"accounts": "admin", "pwd":"123456""type": "username"}
json_data = json.dumps(data)
#添加header
hearder = {'Content-Type':'application/json;charset=utf-8'}
res = requests.post(url, hearders=hearder,params=public_data,data=json_data)	
print(res.json())	
#断言
exData = '登录成功'
reData = jsonpath.jsonpath(res.json(),'$.msg')[0]
assert exData == reData,'期望结果是:{0}','实际结果是{1}'.format(exData,reData)

接口关联

url = "http://shop.com/index.php?s=/api/user/login"
#公共参数
public_data = {"application": "app","application_client_type": "weixin"}
#以content-type='application/json'类型传参
data = {"accounts": "admin", "pwd":"123456""type": "username"}
json_data = json.dumps(data)
#添加header
hearder = {'Content-Type':'application/json;charset=utf-8'}
res = requests.post(url, hearders=hearder,params=public_data,data=json_data)	
print(res.json())	
token = jsonpath.jsonpath(res.json(),'$..token')[0]
#添加购物
data = {
	'goods':'10',
	'spec':'',
	'stock':1
}
params = {
	"application": "app",
	"application_client_type": "weixin",
	"token":token
}
res = requests.post('http://shop.com/index.php?s=api/cart/save',params=params,data=data)
print(res.json())
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值