I want to retrieve an arraylist with all the ids of the users that have a specific email domain (exe: @generatedEmail.com)
This is an example of how the json would look like; basically a Json Array with Json objects.I need to get a list with the ids of the objects that contain @generatedEmail.com in the email field.
[{
"id": "1234-5678-7890-1231",
"email": "[email protected]",
}, {
"id": "gsdg4-fc32-dsfs-4213",
"email": "[email protected]",
},{
"id": "pgo4-ffx2-621s-gju3",
"email": "[email protected]",
}]
My end purpose is to pass this list of ids as parameters to a DELETE endpoint. I found in the Karate documentation that if I pass the list as a parameter when I call the feature file where I describe the Delete steps, it will act as a for each and fire the request for each id in the list.
Thank you in advance!
I tried with different Js functions, but I suck at it and had no success. The below returns to me the emails, but I don't know how to get their related ids. I thought to do the same thing with the ids then match them based on index, but I feel that I would be overengineering it and there must be something simpler and smarter.
* def emails = karate.jsonPath(usersList.response,"$..email")
* def condition = function(x){return x.includes('generatedEmail.com')}
I also tried this with the belief that I would get an array of the objects that I want from which I can later extract only the ids in another arraylist:
* def ids = []
* def fun = function(i){if(i.includes('generatedEmail')) {ids.add(i)}}
* karate.repeat(usersList.response, fun)
Then I also tried this but to no avail
* eval karate.forEach(usersList.response, function(user){if(user.email.includes('generatedEmail')) { ids.add(user.id)} })
Please forgive my lack of knowledge and ignorance :D
CodePudding user response:
I figured out the answer to my question.
The function filters and returns all json objects that contain the 'generatedEmail.com' pattern in their email fields.
Then I use the returned list and deepscan it to only retrieve the id fields in another list.
* def condition = function(x){return x.email.includes('generatedEmail.com')}
* def filtered = karate.filter(response, condition)
* def ids = karate.jsonPath(filtered,"$..id")
CodePudding user response:
Just for your reference, you can do this in one-line if you are familiar with JS. It is elegant and kind of fun:
* def response =
"""
[
{
id: '1234-5678-7890-1231',
email: '[email protected]'
},
{
id: 'gsdg4-fc32-dsfs-4213',
email: '[email protected]'
},
{
id: 'pgo4-ffx2-621s-gju3',
email: '[email protected]'
}
]
"""
* def filtered = response.filter(x => x.email.includes('@generatedEmail.com')).map(x => x.id)
* match filtered == ['1234-5678-7890-1231', 'gsdg4-fc32-dsfs-4213']