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

Postman中从响应体自动创建变量?脚本调用identifier失败求助

修正Postman Tests脚本:根据响应体的identifier和role自动设置变量

原脚本的错误点

  1. 遍历对象错误:原脚本直接遍历整个响应JSON对象(包含timestamp和data字段),但实际需要遍历的是data.endpoints数组,原循环中的responseBody根本没有identifier属性,导致无法进入判断逻辑。
  2. 判断语法逻辑混乱:responseBody.identifier['data'][1]['identifier']这种写法完全不符合响应体的结构,每个端点对象直接通过.identifier和.role即可访问对应字段。

正确的脚本实现

以下脚本会遍历所有端点,根据identifier和role生成唯一的全局变量名,避免相同identifier不同role的变量被覆盖:

// 解析响应体,获取endpoints数组
const endpoints = pm.response.json().data.endpoints;

// 遍历每个端点对象
_.each(endpoints, (endpoint) => {
    // 组合变量名:identifier + 小写role + url,比如credentials_sender_url
    const variableName = `${endpoint.identifier}_${endpoint.role.toLowerCase()}_url`;
    pm.globals.set(variableName, endpoint.url);

    // 如果你需要单独为某个identifier设置固定变量名(如原脚本中的tariffs_url),可以添加额外判断
    if (endpoint.identifier === "tariffs") {
        pm.globals.set("tariffs_url", endpoint.url);
    }
});

按需调整的版本(仅处理特定identifier)

如果只需要处理指定的几个identifier,可以用switch语句精准控制:

const endpoints = pm.response.json().data.endpoints;

_.each(endpoints, (endpoint) => {
    switch(endpoint.identifier) {
        case "credentials":
            pm.globals.set(`credentials_${endpoint.role.toLowerCase()}_url`, endpoint.url);
            break;
        case "tokens":
            pm.globals.set(`tokens_${endpoint.role.toLowerCase()}_url`, endpoint.url);
            break;
        case "tariffs":
            pm.globals.set("tariffs_url", endpoint.url);
            break;
        // 可添加更多需要处理的identifier
    }
});

内容的提问来源于stack exchange,提问作者pedro.ribeiro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:15:47