1

Karate : Is there a way yo get a specific value as a string instead of an array when using jsonPath

My Requirement is i'm trying to get a specific value from the response and trying to assign it to another variable using jsonPath. but the value is being stored as an array value. Instead i need that value to be stores as a String so that i can use it in next request as a query param

{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
    "streetAddress": "naist street",
    "city": "Nara",
    "postalCode": "630-0192"
},
"phoneNumbers": [
    {
        "type": "iPhone",
        "number": "0123-4567-8888"
    },
    {
        "type": "home",
        "number": "0123-4567-8910"
    }
]}

using following jsonPath --$.[?(@.type == 'home')].number i'm getting ["0123-4567-8910"]. But what i need is to store only the number(0123-4567-8910) directly.

1 Answers1

1

Here's the solution. Note that a JsonPath query always returns an array, you need to "un pack" it:

* def numbers = $.phoneNumbers[?(@.type == 'home')].number
* def number = numbers[0]
* match number == '0123-4567-8910'

For completeness, here is a way to do this using only JavaScript:

* def found = response.phoneNumbers.find(x => x.type == 'home').number
* match found == '0123-4567-8910'
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Tried the above Javascript Solution, but getting the following error. Not sure if I'm missing anything here feature:31 - Failed generating bytecode for :1 – Smith Regan Jun 22 '22 at 04:39
  • in such cases I can't help unless you follow this process: https://github.com/karatelabs/karate/wiki/How-to-Submit-an-Issue – Peter Thomas Jun 22 '22 at 05:22