Postman中从响应体自动创建变量?脚本调用identifier失败求助
修正Postman Tests脚本:根据响应体的identifier和role自动设置变量
原脚本的错误点
- 遍历对象错误:原脚本直接遍历整个响应JSON对象(包含
timestamp和data字段),但实际需要遍历的是data.endpoints数组,原循环中的responseBody根本没有identifier属性,导致无法进入判断逻辑。 - 判断语法逻辑混乱:
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
相关产品推荐
相关产品推荐

