Easy Javascript Question - getting value from JSON

Hi:

What would be the proper script for pulling the “.id” from the 2nd member “name: wakanda” from the below quoted JSON sample?

Basically, I need to be able to go through all the members of this JSON object and test if the .name begins/contains “wakanda” . If it does, i write to an environment variable with "AuthorizationServerId: “Value of ID”

Lets assume this JSON contains a bunch of members (not just the two in the below sample.

[
{
“id”: “aus1d5w434jv2qFgW2p7”,
“name”: “default”,
“description”: “Default Authorization Server for your Applications”,
“audiences”: [
“api://default”
],
“issuer”: “https://wakanda.okta.com/oauth2/default”,
“status”: “ACTIVE”,
“created”: “2018-06-12T16:00:16.000Z”,
“lastUpdated”: “2018-06-12T16:00:16.000Z”,
“credentials”: {
“signing”: {
“rotationMode”: “AUTO”,
“lastRotated”: “2018-06-12T16:00:16.000Z”,
“nextRotation”: “2018-09-10T16:00:16.000Z”,
“kid”: “It1zc8es8Lh6-gAsOlH9Z-nmA2HC0ys5_6gCN7FXZK8”
}
}
},
{
“id”: “aus1dfrdn0Gvwq0Tc2p7”,
“name”: “wakanda”,
“description”: “Broad audience for wakanda”,
“audiences”: [
“wakanda”
],
“issuer”: “https://wakanda.okta.com/oauth2/aus1dfrdn0Gvwq0Tc2p7”,
“status”: “ACTIVE”,
“created”: “2018-06-13T01:03:42.000Z”,
“lastUpdated”: “2018-06-13T01:03:42.000Z”,
“credentials”: {
“signing”: {
“rotationMode”: “AUTO”,
“lastRotated”: “2018-06-13T01:03:42.000Z”,
“nextRotation”: “2018-09-11T01:03:42.000Z”,
“kid”: “5dhkhiVOzjYGG1aBxWca5DxYN90XIVjugJB0vzJF8Wg”
}
}
}
]

Of course, I start off with a “var jsonData = JSON.parse(responseBody);”

my test outline is:

if jsonData.name != “wakanda”
// do nothing
//if name = wakanda , write id to variable
postman.setEnvironmentVariable(“authorizationServerId”, ‘"’ + jsonData.id + ‘"’);

This is the closest I have been able to get to it - using lodash:

var jsonData = JSON.parse(responseBody);
var matches = _.where ({name : “wakanda”});
console.log(“here are our matches” , matches);
pm.environment.set(“AuthorizationServerId”, matches.id);

Unfortunately, this does not work . The resultant object is:

Response Body:
0:
1:
id:“aus1dfrdn0Gvwq0Tc2p7”
name:“wakanda”
description:“Broad audience for wakanda”
audiences:
issuer:“https://wakanda.okta.com/oauth2/aus1dfrdn0Gvwq0Tc2p7”
status:“ACTIVE”
created:“2018-06-13T01:03:42.000Z”
lastUpdated:“2018-06-13T01:03:42.000Z”
credentials:
_links:
200
483 ms

here are our matches

Array:[]
0:“wakanda”

Can’t you just loop through the list of members with forEach and set your requirements in an if-statement?

let jsonData = JSON.parse(responseBody);

jsonData.list.forEach((id) => {
 if(id.name.includes('wakanda')) {
   pm.environment.set('AuthorizationServerId', id.id);
} else {
 //do nothing
}
});
1 Like