Reputation: 4334
I require a little guidance on trying to find a list of values from a JSON response.
I have a JSON that looks like this below:
"reviewRatingCount": [
{
"id": 1,
"name": "xxx",
"value": x,
"percentage": 8.49
},
{
"id": 2,
"name": "xxx",
"value": x,
"percentage": 11.19
},
{
"id": 3,
"name": "xxx",
"value": x,
"percentage": 22.74
}
...
Now I have performed a check to ensure 'ReviewRatingCount' does not equal null:
def reviewratingcount = json.reviewratingcount
assert reviewratingcount != null
What I want to do is ensure that the ids within this 'reviewRatingCount' equals 1, 2, 3. So virtually i want it to iterate through the ids within the reviewRatingCount and ensure all the ids contain the correct values. How is this applied in groovy scripting so then I can apply it to not only this example, but also for the other checks like 'name'?
Thank you.
Upvotes: 3
Views: 5512
Reputation: 84854
No need to iterate, use *
operator:
import groovy.json.JsonSlurper
def json = '''{"reviewRatingCount": [
{
"id": 1,
"name": "Terrible",
"value": 214,
"percentage": 8.49
},
{
"id": 2,
"name": "Poor",
"value": 282,
"percentage": 11.19
},
{
"id": 3,
"name": "Average",
"value": 573,
"percentage": 22.74
}
]}'''
def slurped = new JsonSlurper().parseText(json)
assert slurped.reviewRatingCount*.id == [1, 2, 3]
Upvotes: 3