参考官网教程:
https://jmespath.org/tutorial.html
jmespath 可以用来提取数据,在进行上下游传参,以及做断言的时候都可以使用。
JMeter 接口测试工具中也支持jmespath
使用场景主要是当服务器返回结果特别多的时候。
JMeter中使用 JMESpath
jmeter的基本使用教程
https://www.bilibili.com/video/BV11B4y1P7nr/
JMESpath进行数据提取。在JMeter中创建新建http请求
请求路径为: http://49.233.108.117:28019/api/v1/index-infos
添加查看结果树,运行。查看结果
选择【JSON JMESPath Tester】
使用 JMESPath 提取返回结果中 推荐商品 商品价格大于3000元的商品id
data.recommendGoodses[?sellingPrice>`3000`].goodsId

从返回结果中提取变量
添加对应的路径表达式
python中使用JMESPath
参考文档: https://github.com/jmespath/jmespath.py
安装jmespath
pip install jmespath
接口中的应用
从商品首页中提取服务器的结果
import requestsr = requests.get("http://49.233.108.117:28019/api/v1/index-infos")# print(r.json())# 提取 推荐商品中价格 大于 3000的商品id# 使用原始的数据解析方法# 声明空的列表test_goods_ids = []result = r.json()# 循环服务器返回的结果for goods in result["data"]["recommendGoodses"]:# print(goods["sellingPrice"])# 如果商品的价格大于3000if goods["sellingPrice"] > 3000:# 将此商品对应的id放在列表中test_goods_ids.append(goods["goodsId"])print(test_goods_ids)
使用 JMESpath 的方式进行提取
import requestsr = requests.get("http://49.233.108.117:28019/api/v1/index-infos")import jmespath# jmespath 表达式exp = "data.recommendGoodses[?sellingPrice>`3000`].goodsId"goods_ids = jmespath.search(exp,r.json())print(goods_ids)
可以看到,两种方式结果都一样。只是代码量的 不一样。
需要注意的是: 这里数字使用的是 反向的单引号。
