My question: I want to capture data from three objects in a JSON response, however, two of the objects are always in the response, and one is not always there (by design). Additionally, the first two objects that are always there (notificationId
& receiptHandle
), are inside an array, and the 3rd object (actionUrl
) is nested inside a second array (if it exists).
When I try to set these three variables using my normal method, shown below, postman errors out when it cannot find the actionUrl
and hence none of the variables are set (even though the other two are present)
let jsonData = pm.response.json();
let notificationId = jsonData.notifications[0].notification.id;
pm.environment.set("notification_id", notificationId);
let receiptHandle = jsonData.notifications[0].receiptHandle;
pm.environment.set("receipt_handle", receiptHandle);
let terminalActionUrl = jsonData.notifications[0].notification.message.data.actions[0].href;
pm.environment.set("action_url", actionUrl);
When I submit the above I get:
TypeError: Cannot read properties of undefined (reading '0')
When the data for all 3 objects is in the response, everything gets saved correctly. And if I remove the 3rd variable it saves the first two fine.
So, I am hoping someone can help me with writing an IF statement for the third variable (the actionsUrl
) so that it only tries to set it if it’s found (in the nested array) but I cannot seem to get it to work (after trying many many variations and searching on this and other forums…)
Here’s an example of what the JSON response looks like with just the first two data points available:
{
"notifications": [
{
"receiptHandle": "{some hash code}",
"notification": {
"id": "{some GUID}",
"message": {
"id": "{some GUID}",
"data": {
"some": "data"
}
}
}
}
]
}
And here’s an example of it with all three:
{
"notifications": [
{
"receiptHandle": "{some hash code}",
"notification": {
"id": "{some GUID}",
"message": {
"id": "{some GUID}",
"data": {
"some": "data",
"actions": [
{
"href": "{some URL}"
}
]
}
}
}
}
]
}