1

I would like to get the value from the response based on a condition and store it to a variable.

In the below JSON, I would like to store the value when the name matches to something I prefer. Is there a way to achieve this using Karate API?

{
  "results": [
    {
      "name": "Sample1",
      "email": "sample1@text.com",
      "id": "U-123"
    },
    {
      "name": "Sample2",
      "email": "sample2@text.com",
      "id": "U-456"
    },
    {
      "name": "Sample3",
      "email": "sample3@text.com",
      "id": "U-789"
    }
  ]
}
janw
  • 8,758
  • 11
  • 40
  • 62

1 Answers1

0

So after reading the comment, my interpretation is to "find" the id where name is Sample2. Easy, just use a filter() operation, refer the docs: https://github.com/karatelabs/karate#jsonpath-filters

Instead of using a filter, I'm using the JS Array find() method as a very concise example below:

* def response =
"""
{ "results": [
    { "name": "Sample1", "email": "sample1@text.com", "id": "U-123" },
    { "name": "Sample2", "email": "sample2@text.com", "id": "U-456" },
    { "name": "Sample3", "email": "sample3@text.com", "id": "U-789" }
  ]
}
"""
* def id = response.results.find(x => x.name == 'Sample2').id
* match id == 'U-456'

Take some time to understand how it works. Talk to someone who knows JS if needed.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248