Reputation: 49
I have a postman json response and within the array the position of a specific variable changes. Based on my response below i need to write a test to loop through the response the first sighting of optionLabel with value "2 Pax Min". Save its "id" i.e BBBB in the environment variable
I have tried this
var jsonData = JSON.parse(responseBody);
jsonData[[0].optionSet.options].forEach(function(arroption) {
if (arroption.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(arroption.id));
}
});
My Response
[
{
"id": "",
"date": "2019-08-21",
"optionSet": {
"optionSetLabel": "Options",
"options": [
{
"id": "A",
"optionLabel": "QUAD Rm"
},
{
"id": "AA",
"optionLabel": "QUAD Rm with post Accom"
},
{
"id": "AAA",
"optionLabel": "Rm 3 Pax Min"
},
{
"id": "AAAA",
"optionLabel": "4 Pax Min"
}
]
}
},
{
"id": "",
"date": "2019-08-22",
"optionSet": {
"optionSetLabel": "Options",
"options": [
{
"id": "B",
"optionLabel": "QUAD Rm"
},
{
"id": "BB",
"optionLabel": "QUAD Rm with post Accom"
},
{
"id": "BBB",
"optionLabel": "SGL Rm with post Accom"
},
{
"id": "BBBB",
"optionLabel": "2 Pax Min"
}
]
}
}
]
My end result is i want to save the id "BBBB" in the environment variable
Upvotes: 1
Views: 436
Reputation: 25881
Mickael's answer should be the accepted solution (I upvoted it) but I just wanted to offer the same thing done with Lodash, which is built-in to Postman.
_.each(pm.response.json(), (data) => {
_.each(data.optionSet.options, (option) => {
if (option.optionLabel === '2 Pax Min') {
pm.environment.set("pax", option.id);
}
})
})
I see lots of answers that do this var jsonData = JSON.parse(responseBody);
to parse the response body but it's the same as just using the newer pm.*
API function pm.response.json()
to do the same thing.
https://learning.getpostman.com/docs/postman/scripts/postman_sandbox_api_reference/
Upvotes: 0
Reputation: 5205
You have a braket problem here jsonData[[0].optionSet.options]
.
Maybe you wanted to do something like jsonData[0].optionSet.options
or jsonData[1].optionSet.options
Here this code should do what you want
for (let data of jsonData) {
for (let option of data.optionSet.options) {
if (option.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(option.id));
}
}
}
Same with forEach
rather than for
loop
jsonData.forEach(function(data) {
data.optionSet.options.forEach(function(arroption) {
if (arroption.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(arroption.id));
}
})
})
Upvotes: 1