json - 如果响应正文中的 id 具有依赖性,如何使用预请求脚本在邮递员中设置 2 个集合变量?
问题描述
我正在尝试通过从响应正文中选择 id 来使用预请求脚本在邮递员中设置 2 个集合变量。有两个 id,即 id 和 subId,只有当 id 链接到 subId 时,我才需要在集合变量中设置这两个 id。
需要从下面的 json 响应中获取 id 和 subId(可能有多个记录,其中 id 没有 subId 值)。请帮我解决这个问题。
{
"result": [
{
"id": 26,
"name": "Testing",
"code": "TST-012",
"branches": [
{
"emailId": null,
"country": {
"shortName": "Niu",
"currency": "New Zealand Dollar"
}
}
],
"subId": [
{
"id": 46,
"name": "qa",
"code": "qa"
}
]
},
{
"id": 27,
"name": "Testing",
"code": "TST-012",
"branches": [
{
"emailId": null,
"country": {
"shortName": "US",
"currency": "US Dollar"
}
}
],
"subId": null
}
]
}
解决方案
id
包含subId
非空的提取
const res = pm.response.json();
const matchEle = res.result.find(e => e.subId !== null);
pm.collectionVariables.set("id", matchEle.id); //26
id
里面提取subId
- 如果获取所有 id
const subIds = _.map(matchEle.subId, _.property("id"));
pm.collectionVariables.set("subIds", JSON.stringify(subIds)); //[46]
- 如果只获得第一个 id
pm.collectionVariables.set("subId", matchEle.subId[0].id); //46
推荐阅读
- three.js - WebGL 是否有统一或纹理绑定限制?
- javascript - 是否可以使用 javascript 显示用户图像而无需将它们保存到某个后端?
- acumatica - 更改列过滤器的默认选项
- python - ImportError:动态模块没有定义模块导出函数(PyInit_cv_bridge_boost)
- ssl - telegram bot webhook 自签名证书问题
- python - Jupyter 实验室:UnicodeDecodeError:“charmap”编解码器在启动时无法解码字节
- angular - 如何在 Angular 中为来自 API 的响应编写单元测试
- asp.net-mvc - 实体框架尝试在已经存在的生产服务器上创建数据库
- node.js - 使用带有 npm 的护照包可以从客户端更改 req.user 对象吗?
- angular - Angular - 用于同一组件中的两个元素时,ngx剪贴板抛出错误