Karan
Karan

Reputation: 33

How to find dynamic key values in Karate?

I am hitting JIRA API to fetch cycle id based on cycle name

API : http://localhost:8080/rest/zapi/latest/cycle?projectId=78654&versionId=123

and I am getting following response:

{

"1345": {
    "totalExecutions": 0,
    "endDate": "",
    "description": "",
    "versionName": "Unscheduled",
    "projectKey": "ABC",
    "totalDefects": 0,
    "versionId": 123,
    "name": "First cycle",
    "totalFolders": 0,
    "projectId": 78654
},
"5789": {
    "totalExecutions": 0,
    "endDate": "",
    "description": "",
    "versionName": "Unscheduled",
    "projectKey": "ABC",
    "totalDefects": 0,
    "versionId": 123,
    "name": "Karate DEMO",
    "totalFolders": 0,
    "projectId": 78654
},
"6543": {
    "totalExecutions": 0,
    "endDate": "",
    "description": "",
    "versionName": "Unscheduled",
    "projectKey": "ABC",
    "totalDefects": 0,
    "versionId": 123,
    "name": "Second Cycle",
    "totalFolders": 0,
    "projectId": 78654
},
"recordsCount": 3
}

Here Id's are dynamic i.e. 1345,5789,6543

How do I fetch Id i.e. 5789 where name is "Karate DEMO" using karate jsonpath

Upvotes: 3

Views: 995

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

Use a JSON transform to change the shape which makes it easier to do JsonPath. You can also find data because karate.forEach() is a "scan": https://github.com/intuit/karate#json-transforms

* def list = []
* def fun = function(k, v){ karate.appendTo('list', { key: k, val: v } )}
* karate.forEach(response, fun)
* def keys = $list[?(@.val.name=='Karate DEMO')].key

Upvotes: 2

Related Questions