Reputation: 163
API response example:
{
"topic1": [
{"fieldName2": "value2",fieldName1": "value1"}
],
"topic2": [
{"fieldName2": "value2","fieldName1": "value1"},
{"fieldName2":"anotherValue2","fieldName1": "anotherValue1"}
]
}
This will work:
Then match response.topic1 == [{"fieldName2": "value2",fieldName1": "value1"}]
And match response == {"topic1":[{"fieldName2": "value2",fieldName1": "value1"}]}
But I need "topic1" to be in a variable like this but cant find a way to make it work.
Then match response.TOPIC_NAME== [{"fieldName2": "value2",fieldName1": "value1"}]
Also tried response.<TOPIC_NAME>
and match response contains
message only but also not working.
* print "KAFKA_TOPIC: ", KAFKA_TOPIC
* print "response.KAFKA_TOPIC:", response.KAFKA_TOPIC
* print "response.topic1: ", response.topic1
Logs:
11:47:47.946 [main] INFO com.intuit.karate - [print] KAFKA_TOPIC: topic1
11:47:47.949 [main] INFO com.intuit.karate - [print] response.KAFKA_TOPIC: null
11:47:47.951 [main] INFO com.intuit.karate - [print] response.topic1: [
{
"fieldName1": "value1",
"fieldName2": "value2",
"fieldName2": "value3"
}
]
Trying now to explore https://github.com/karatelabs/karate#json-transforms if there's no direct approach.
Upvotes: 1
Views: 1365
Reputation: 58058
You can access JSON with dynamic keys like this: object[keyName]
. This is just JS behind the scenes. This example should make your options clear:
* def response =
"""
{
"topic1": [
{
"field1": "value1"
}
]
}
"""
* def key1 = 'topic1'
* def val1 = response[key1]
* match val1 == [{ field1: 'value1' }]
# to do this in one line
* match (response[key1]) == [{ field1: 'value1' }]
Upvotes: 1