Home > OS >  How do I capture a specific array element from json response into a gherkin cucumber attribute?
How do I capture a specific array element from json response into a gherkin cucumber attribute?

Time:04-13

Am trying to capture from below json response, the ghi[0] element which is x and assign it to a variable in my BDD in gherkin/cucumber language but it is complaining it can't read property.

This is how am capturing:

* def xyz = response.results.payload.abc.def.ghi

Response

{
    "results": {
        "payload": {
            "abc": [
                {
                    "def": [
                        {
                            "ghi": "x",
                        },
                        {
                            "ghi": "y",
                        },
                        {
                            "ghi": "y",
                        }
                    ]
                }
            ]
        }
    }
}

This is what its complaining:

features.blah: [1.1:50] blah.feature:30 - evaluation (js) failed: response.results.payload.abc.def.ghi, javax.script.ScriptException: TypeError: Cannot read property "ghi" from undefined in <eval> at line number 1

CodePudding user response:

That's because your access is wrong. This below works:

* def xyz = response.results.payload.abc[0].def[0].ghi
* match xyz == 'x'

That said, if you are lazy to traverse deeply nested data, you can do this:

* def xyz = get[0] $..ghi
* match xyz == 'x'

Please read the docs, it will save you time :) https://github.com/karatelabs/karate#get

  • Related