1

I would like to print the index value for matching JSON data using Karate.

For below code the expected answer should be 2, but I got -1, not sure what I am missing

[
  {"aaa": 101},
  {"bbb": 102},
  {"ccc": 103}
]
Feature: Rough

  Scenario: Rough
    * def myData = read('roughTestData.json')
    * print "Index ->>", myData.indexOf('ccc')
kumar
  • 13
  • 3

1 Answers1

0

You have a JSON object within an array (not a plain string), and the complication here is you are interested in keys not values, so you need to do this instead:

* def response = [{"aaa":101},{"bbb":102},{"ccc":103}]
* def keys = response.map(x => Object.keys(x)[0])
* def index = keys.indexOf('ccc')
* match index == 2

We are using JS array methods such as map(), Object.keys() and indexOf() above

That said, I personally think you are over-complicating things because Karate allows you to match without caring about the order. For example:

* def response = [{"aaa":101},{"bbb":102},{"ccc":103}]
* def expected = [{ccc:'#number'},{bbb:'#number'},{aaa:'#number'}]
* match response contains only expected

So read the docs, and be creative: https://github.com/karatelabs/karate#json-arrays

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248