Reputation: 1500
I have an API that returns an JSON array of objects, where one of fields contains escaped JSON. Let's say it looks like that:
{
"results":[
{
"id": "id-1",
"data": "{\"name\", \"Adam\", \"surname\": \"Parker\"}"
},
{
"id": "id-2",
"data": "{\"name\", \"Adam\", \"surname\": \"Parker-Bates\"}"
},
{
"id": "id-3",
"data": "{\"name\", \"Adam Robert\", \"surname\": \"Parker\"}"
}
]
}
Now, I need to assert that that array contains exactly one element matching given criteria, let's say I'm looking for Adam Parker
. If it would be returned as a proper JSON object it would be pretty straightforward. I could search for substrings, but it can give me false results. Maybe I could look for certain regular expressions to match only \"Adam\"
and "\Parker\"
but would prefer to convert that strings to JSON objects, since real case scenario has much more complex, nested data. Is there any way to do it with karate? I do not need ids, so I can extract data to array of strings if that would make it easier.
Upvotes: 1
Views: 4456
Reputation: 58058
That's easy, Karate has a few helper functions hanging off the karate
JS object: https://github.com/karatelabs/karate#the-karate-object
By the way your JSON is not well-formed (comma instead of colon) which got me stuck for a while.
Here's a demo, also refer the documentation on how to do JSON transforms, we are using JS array methods below: https://github.com/karatelabs/karate#json-transforms
* def response =
"""
{
"results":[
{
"id": "id-1",
"data": "{\"name\": \"Adam\", \"surname\": \"Parker\"}"
},
{
"id": "id-2",
"data": "{\"name\": \"Adam\", \"surname\": \"Parker-Bates\"}"
},
{
"id": "id-3",
"data": "{\"name\": \"Adam Robert\", \"surname\": \"Parker\"}"
}
]
}
"""
* def names = response.results.map(x => karate.fromString(x.data))
* match names contains { name: 'Adam', surname: 'Parker' }
Upvotes: 1