String contains in if statement

Hi,

I have a response from one of the endpoints like below

{
    "links": [
        "First String",
        "Second String"
    ]
}

Some times the values will be interchanged in the response.

Now I need to store only the Second String in the Environment Variable so I wanted to use if condition and if it satisfies the condition then store it.

But I don’t know how to do it.
Can anyone help with if condition how to write in tests

Hey @ereddy068

If there will always be 2 items in that array and you only want the second one each time:

pm.environment.set('my_value', pm.response.json().links[1])

It’s zero indexed so the second item would be [1], which I know looks kinda silly. :grinning_face_with_smiling_eyes:

That would break under several conditions though but i"m not aware of the full context.

1 Like

Hi @danny-dainton ,
Thank you for your response.
Yes there will be only 2 values, but the values will be interchanged in the response so there is no guarantee I will have Second String in 2nd place.

So before assigning the value I need to compare them

Not really sure what you’re comparing them with…each other? Something else? :grin:

Is the value, a set/known value or does that also change?

seems like the issue is with whatever is producing the data, it isn’t in a predictable order. Not sure Postman can fix that.

I did like this and issue is solved
var data = JSON.parse(responseBody);
var temp=data.links[0];
if(temp.includes(“accounts”)){
postman.setEnvironmentVariable(“variable”, data.links[0]);
}
else{
postman.setEnvironmentVariable(“variable”, data.links[1]);
}

I think you know, but this isn’t a reliable way to program this. I think you’re assuming the string value “accounts” will always return, and that it’s only ever going to be an array of two. If the data in your response array changes and ‘accounts’ doesn’t exist, you’re going to get an error.

I assume if you’re writing this test in this way, it’s because your interface needs to be able to do the same thing (tell the array list items apart to show a specific one). They will have an issue getting the information reliably, too, so it would still be a good idea to open a bug ticket with your API team to get them to send the data consistently and predictably. I would even go as far as to request an architectural change (if it were me) in this situation, so that you (and your interface) receive a key:value pair for each link and can properly index it, rather than string comparing in a for-loop through the array. But to each their own.