rahoolm
rahoolm

Reputation: 773

How to filter a complex response in karate dsl using jsonPath?

I am getting below response from a REST API, but I am finding it difficult to extract label value from the received response and assign it to a variable to use it later in script.
Here is the RESPONSE::

{
  "result": "SUCCESS",
  "rawAttr": "[{\"attributes\":[{\"name\":\"resourceid\",\"value\":\"7A7Q123456\"},{\"name\":\"physicalid\",\"value\":\"7A7Q123456\"},{\"name\":\"dsw:label\",\"value\":\"MY Product00004285\"},{\"name\":\"dsw:created\",\"value\":\"2019-11-06T08:39:39Z\"}]}]",
  "physicalid": "7A7Q123456",
  "contextPath": "/path",
  "id": "7A7Q123456",
  "message": null
}

I am able to get response.id and response.result which is helpful for validation but I am not able to get the dsw:label value which is MY Product00004285

When I do def Arr = response.rawAttr I get the below value whether it is Array or String I am confused. Seems like it is a string.

[{"attributes":[{"name":"resourceid","value":"7A7Q123456"},{"name":"physicalid","value":"7A7Q123456"},{"name":"dsw:label","value":"MY Product00004298"},{"name":"dsw:created","value":"2019-11-06T08:39:39Z"}]}]

It is very easy to extract the label in JMeter JSON Extractor using below JSON Path expression $.attributes.value[2]

Upvotes: 1

Views: 1966

Answers (2)

rahoolm
rahoolm

Reputation: 773

Thanks to an example and documentation on converting string to json.
Got it how to do.

And def strVar = response.rawAttr
And json jsonVar = strVar
And def attrb = karate.jsonPath(jsonVar, '$..attributes.[2].value')[0]
And print '\n\n Attrb\n', attrb

Links I referred:
Json Path evaluator
Karate doc reference for type conversion
Karate example for type-conversion

Upvotes: 0

Peter Thomas
Peter Thomas

Reputation: 58153

Refer Karate's type conversion capabilities: https://github.com/intuit/karate#type-conversion

So you can do this:

* json attr = response.rawAttr

And then you are all set.

Upvotes: 1

Related Questions