1

Is there a way to match the response data from API which contain a nested array for a key where key-value pair are in different order inside the nested array in karate?

Scenario: Verify original data contains expected data

  • def original = [{ a:1, b: [{c:2},{d:3}]}]
  • def expected = [{ b: [{d:3},{c:2}], a:1 }]

Using contains deep method will solve the issue but I am expecting original data from a API response so in some point of time if one more field gets added to the API response, then my scenario will still get passed

Harish
  • 35
  • 4

1 Answers1

1

Don't try to do everything in one-line. Split your matches, and there is more explanation in the docs:

* def inner =  [{ c: 2 }, { d: 3 }]
* def response = [{ a: 1, b: [{ d: 3 }, { c: 2 }]}]

* match each response contains { b: '#(^^inner)' }
* match each response == { a: 1, b: '#(^^inner)' }
* match response[0] == { a: 1, b: '#(^^inner)' }
* match response == [{ a: 1, b: '#(^^inner)' }]

You don't need to use all of these, I'm showing the possible options.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Thanks for your answer. But I am actually trying to match the response I am getting from an API call with the data present in a JSON file. But in karate sometimes fields in the API response are getting shuffled and if fields get shuffled inside an array then the match operator will fail to validate the API response with the data from a JSON file – Harish Aug 09 '22 at 06:51
  • @Harish I suggest you accept this answer. then please ask a new question, and this time make clear with a (simple) example what your question is. I am unable to make sense of your comment or question. and I hope you understood that the `#(^^foo)` is a `CONTAINS ONLY` match and order will not matter. did you try my solution at all ? did you read the docs ? https://github.com/karatelabs/karate#schema-validation – Peter Thomas Aug 09 '22 at 06:55
  • 1
    @ Peter Thomas I tried the solution which you mentioned. Thank you for your suggestion regarding framing the question, I will correct it next time – Harish Aug 09 '22 at 07:15
  • @PeterThomas I went through github.com/karatelabs/karate#schema-validation. I was not able to find schema validation for contains only deep, like it is there for ^+ contains deep. Could you please suggest how to use contains only deep? – Surya Mar 30 '23 at 06:08
  • @Surya I think `contains only deep` is not supported via a short-cur. can you ask a question with a clear and *simple* example, we can see if there are other ways to solve this. if we are convinced this is a valid thing to support - we can open a feature request – Peter Thomas Mar 30 '23 at 07:42
  • @PeterThomas Please find my scenario here: https://stackoverflow.com/questions/75885665/karate-schema-validation-in-multi-level-nested-array – Surya Mar 30 '23 at 08:13