Home > Mobile >  Using Karate, how do I loop though a json to pick up the value for a key based on another key in tha
Using Karate, how do I loop though a json to pick up the value for a key based on another key in tha

Time:05-06

Below is the JSON response I get from which I want to extract y1. Before getting the response, I know x1 already but I don't know y1. So for that particular x key element, I want to get its y value (in this case y1).

My json response looks like this:

{
    "result": [
        {
            "x": "x1",
            "y": "y1"
        },
        {
            "x": "x2",
            "y": "y2"
        }
    ]
}

Below is what I am trying in Karate but it seems it picks up null instead:

* def y = get[0] response..result[?(@.x=='x')]

I captured x1 from a previous call. Please let me know where I am wrong. Thanks.

CodePudding user response:

Let's say you have stored x1 in a variable called valX from your previous call. You can now use the below to get y1

* def valY = karate.jsonPath(response, "$.result[?(@.x=='"   valX  "')]")[0].y

You could read

CodePudding user response:

Yes, for dynamic JsonPath, please read the docs: https://github.com/karatelabs/karate#jsonpath-filters

In the latest versions of Karate > 1.0, I also recommend using JS to do things like this:

* def xToFind = 'x1'
* def found = response.result.find(o => o.x == xToFind)
* match found == { x: 'x1', y: 'y1' } 
  • Related