Postman中如何提取多个值并作为不同变量存入环境变量?
Postman提取JSON字段存入环境变量实现方法
操作步骤
- 打开目标请求的Tests标签页
- 粘贴对应代码到编辑区域后发送请求即可
实现代码(适配任意长度的duration数组,自动生成resultN变量)
// 解析接口返回的JSON数据 const responseJson = pm.response.json(); // 取出duration数组 const durationList = responseJson.Test1.duration; // 遍历数组,按索引生成result1、result2...变量存入环境 durationList.forEach((item, index) => { pm.environment.set(`result${index + 1}`, item.Value); });
固定取值实现代码(仅针对当前示例两个Value的场景)
如果你确定duration数组永远只有2个元素,可以直接写死索引取值,写法更直观:
const responseJson = pm.response.json(); pm.environment.set("result1", responseJson.Test1.duration[0].Value); pm.environment.set("result2", responseJson.Test1.duration[1].Value);
验证效果
发送请求后,点击Postman右上角的眼睛图标,在当前环境的变量列表中就能看到已保存的result1、result2变量,后续请求可以直接用{{result1}}、{{result2}}的格式调用取值。
内容的提问来源于stack exchange,提问作者Gavendra Singh
相关产品推荐
相关产品推荐

