I am trying to set a postman environment variable based on a specific value in a response.
I'm unsure on code to use use to grab value.
I know I need to set the response as a variable which I have done as follows:
var response = JSON.parse(responseBody);
And I know I can use the following to set my environment variable:
postman.setEnvironmentVariable("category_ref",myVariableName);
Below is a snippet from my response:
{
"id": 45,
"name": "Accommodation",
"description": ""
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": ""
},
I want to grab the "id" value based on "name" value which I will already know.
So an example being I want my code to give me the ID where "name" = "Accommodation"
Edit:
Changed made to original question following answers below.
My Tests code now looks like this:
//Ensure the API Test Category is present
var response = JSON.parse(responseBody);
tests["my test"] = responseBody.has("Accommodation");
//pass in id into variable for delete step
var requiredId = pm.response.json().find(function(element){
if (element.name == "Accommodation"){
return element.id;
}
});
stringId = JSON.stringify(requiredId);
pm.environment.set("category_ref",stringId);
console.log("my string "+stringId);
And my output to console looks like the following which is also the value that is being sent to the category_ref environment variable:
my string {"id":45,"name":"Accommodation","description":""}
The remaining problem is I don't want to return all the elements as it is doing above, I am wanting to return just "45" which is the id value where name = Accommodation.