Search code examples
jsonchaiassertionpostman-pre-request-script

How to set 2 collection variables in postman using pre-request script if the id's in the response body have dependency?


I'm trying to set 2 collections variables in the postman using a pre-request script by picking the id's from response body. There are two id's namely id and subId, I need to set both the id's in the collection variables only if the id is linked to subId.

Need to get id and subId from below json response (there may be multiple records where id doesn't have subId value). Please help me to solve this.

{
    "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
        }
    ]
}

Solution

    1. Extract id that contains subId not null
    const res = pm.response.json();
    
    const matchEle = res.result.find(e => e.subId !== null);
    
    pm.collectionVariables.set("id", matchEle.id); //26
    
    1. Extract id inside subId
    • If get all id
    const subIds = _.map(matchEle.subId, _.property("id"));
    pm.collectionVariables.set("subIds", JSON.stringify(subIds)); //[46]
    
    • If only get first id
    pm.collectionVariables.set("subId", matchEle.subId[0].id); //46