Getting a value from multiple arrays into a single environment variable

What is the best way to get a value from multiple arrays into a single environment variable?

The JSON I’m working with has an array of arrays. I want to extract all occurrences of users.orgs.guids into an environment variable so I can test against it later. I’m thinking to store it comma separated. For example:

My JSON looks like this:

{
    "user": {
        "sourcedId": "foobar",
        "status": "foobar",
        "dateLastModified": "foobar",
        "username": "foobar",
        "givenName": "foobar",
        "middleName": "foobar",
        "familyName": "foobar",
        "role": "foobar",
        "identifier": "foobar",
        "grades": [
            "foobar"
        ],
        "userIds": [
            {
                "type": "foobar",
                "identifier": "foobar"
            }
        ],
        "orgs": [
            {
                "guid": "DC3CC5BB-43C6-4996-9618-866038C698BC",
                "href": "foobar",
                "type": "foobar"
            },
            {
                "guid": "912D34F0-A6E1-48BF-AF9D-2DCBFF259368",
                "href": "foobar",
                "type": "foobar"
            }
        ],
        "agents": [],
        "enabledUser": "foobar"
    }
}

Desired final result is an environment variable set to:
DC3CC5BB-43C6-4996-9618-866038C698BC,912D34F0-A6E1-48BF-AF9D-2DCBFF259368

I’ll then search that variable later for a matching guid.

I’ve gotten as far as honing in on the guids I want with

var data = JSON.parse(responseBody)
data.user.orgs.forEach((element) => console.log((element.guid)))

Your response (once parsed) is an object that has multiple arrays.

The guid’s are in the orgs array (in a single array).

You can create a new array that contains the guids using the javascript map function.

Keep it as an array, its easier to assert against vs a comma separated string.

The test is then a simple includes.

As you have a single user in the response, you might as well parse directly to this element and call the variable user. It helps with legibility.

const user = pm.response.json().user;  // parse directly to the user element

let guids = user.orgs.map(guids => guids.guid);  // creates a new array of guids
// console.log(guids);

let guid = "912D34F0-A6E1-48BF-AF9D-2DCBFF259368";

pm.test(`guids contain ${guid}`, function () {
    pm.expect(guids).to.include(guid);
});

image

If you are going to store them as environment or collection variables. You have to JSON.stringify() the value before storing it, and JSON.parse() it when retrieving. (Otherwise it will be treated as a string instead of an array).

1 Like