Search code examples
karate

Karate : how to get an object from a Json array by checking one of its field


We are testing an API that returns a body that looks like this :

[
  {
    "abc" : "abc",
    "bcd" : "bcd",
    "moduleList": [
      {
        "certificate": {
          "code": "P",
          "idAES": 739296
        },
        "date": "2024-01-01T00:00:00+01:00",
        "idModule": 12345,
        "moduleNumero": 1
      },
      {
        "certificate": {
          "codee": "P",
          "idAES": 9
        },
        "date": "2024-02-08T00:00:00+01:00",
        "idModule": 98729,
        "moduleNumero": 2
      },
      {
        "date": "2024-05-05T00:00:00+02:00",
        "idModule": 109364,
        "moduleNumero": 3
      }
    ],
    "cde": "cde"
  }
]

We have 3 objects in the moduleList. We know that the object that has "moduleNumero":1 should have a "certificate" object inside itself, as well as the object that has "moduleNumero":2 .

The object that has "moduleNumero":3 should not have it.

The problem is that the API doesn't return these objects in this specific order every time, so we can't check by doing "And assert response[0].moduleList[0].certificate == '#present' " because the first in the list could be any of these.

Is there a way to define a variable on the json object that contains "moduleNumero":1 (or 2) so we can then check that the object "certificate" is present in it ?

Is there another way to achieve this assertion ?


Solution

  • Assuming response is only the moduleList array from your example:

    * def modulesWithCert = response.filter(x => x.certificate)
    

    This will get you only the ones with a certificate. I personally prefer this approach instead of JsonPath [*] or filters because it is more readable.

    Refer to other ideas here: https://stackoverflow.com/a/76091034/143475