You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中按条件从JSON响应数组提取值并存入环境变量

Postman 按Type字段提取响应Value并存环境变量方案

操作步骤

  1. 打开目标接口请求的「Tests」标签页,该区域的脚本会在接口收到响应后自动执行
  2. 将以下代码粘贴到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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:36:03