Asserting Nested JSON

Is there a way to assert an array in nested JSON if index is not known. For e.g:
I want to check car2 is “GM”, in below example it is array index 2, but it may not always be at index 2.
something like this doesn’t work: assertThat (cars[*].cars2).isEquals(“GM”)

{
“name”: “John”,
“age”: 30,
“cars”: [{
“car1”: “Ford”,
“car2”: “BMW”,
“car3”: “Fiat”
},
{
“car1”: “Nissan”,
“car2”: “Honda”,
“car3”: “Toyata”
},
{
“car1”: “Chevy”,
“car2”: “GM”,
“car3”: “Kia”
}
]
}

@ssridharan I split your question to a new Topic. Please stick to one question per Topic (it helps others while searching) Also, please go back to the old Topic and post a response to my answer (did it work? If so, please mark the answer as a Solution).

Did you try:

assert cars[2].car2 == "GM"

@Russ_Thomas Noted.

Yes, that works. When I know the index location and pass it, it works flawlessly.
It’s only when I don’t know the index location.

You can use the .find method. Do a search.

I did something like this and got below error:

assert (Cars).find {car2 --> “GM”}

Reason:
groovy.lang.MissingMethodException: No signature of method: groovy.json.internal.LazyMap.previous() is applicable for argument types: () values: []

Nevermind, it worked. Initially, I was sending the parseText value, but tried sending value from JSONBuilder and it worked! Thanks

1 Like