首页 > 解决方案 > 如果响应正文中的 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
        }
    ]
}

标签: jsonchaiassertionpostman-pre-request-script

解决方案


  1. id包含subId非空的提取
const res = pm.response.json();

const matchEle = res.result.find(e => e.subId !== null);

pm.collectionVariables.set("id", matchEle.id); //26
  1. 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

推荐阅读