如何在Postman中按条件从JSON响应数组提取值并存入环境变量
Postman 按Type字段提取响应Value并存环境变量方案
操作步骤
- 打开目标接口请求的「Tests」标签页,该区域的脚本会在接口收到响应后自动执行
- 将以下代码粘贴到Tests编辑区域:
// 解析响应JSON数组 const responseArr = pm.response.json(); // 填写你需要匹配的Type值,示例为CD const targetType = "CD"; // 查找匹配的元素 const targetItem = responseArr.find(item => item.Type === targetType); if(targetItem){ // 按要求拼接变量名并存入环境变量 pm.environment.set(`${targetType}Value`, targetItem.Value); }
效果验证
- 发送请求后,点击Postman右上角的环境变量查看按钮,即可看到新增的
CDValue变量,值为对应匹配到的987789 - 若要批量存储所有Type对应的Value,可将脚本替换为如下版本:
const responseArr = pm.response.json(); responseArr.forEach(item => { pm.environment.set(`${item.Type}Value`, item.Value); })
注意事项
如果需要存入全局变量,将
pm.environment.set替换为pm.globals.set即可
建议添加响应状态判断,避免接口异常时报错,可在代码最外层加如下判断:if(pm.response.code === 200){ // 上述提取逻辑放在这里 }
内容的提问来源于stack exchange,提问作者Gavendra Singh
相关产品推荐
相关产品推荐

