1

How to print two values from the response (array of JSON objects)

I have a test in Karate where the response is an array of JSON objects, all of them include a key called id. and name. I need to print only id -> name from the entire response

I can print a single values like this

  • def id = $response.data[*].id
  • def name = $response.data[*].name

But not sure how to print both values together

I can print a single values like this

  • def id = $response.data[*].id
  • def name = $response.data[*].name

But not sure how to print both values together like

1 - John 2 - David 3 - Tom

1 Answers1

0

It is better to just loop over the array. Note that print also gives you the option to have multiple arguments like karate.log() below:

* response.data.forEach(x => karate.log('id:', x.id, 'name:', x.name)

You should be using Karate to do assertions, not print :)

Another way to approach the problem is to create a new array:

* def temp = response.data.map(x => `${x.id} - ${x.name}`)
* print temp

Refer this answer to understand how the above "loops" work: https://stackoverflow.com/a/76091034/143475

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