Reputation: 183
I've written the following groovy script in SOAPUI to execute an assertion on a JSON response.
I'm having difficulty writing the assertion to extract and assert on Weather > main > Clouds property and value of the JSON response.
Can someone please assist with correcting my code to extract the value I want?
Thanks!
import groovy.json.JsonSlurper
def json = '''{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
"base": "stations",
"main": {
"temp": 281.644,
"pressure": 1027.43,
"humidity": 100,
"temp_min": 281.644,
"temp_max": 281.644,
"sea_level": 1035.14,
"grnd_level": 1027.43
},
"wind": {
"speed": 3.33,
"deg": 43.5005
},
"clouds": {
"all": 12
},
"dt": 1476231232,
"sys": {
"message": 0.0084,
"country": "GB",
"sunrise": 1476253200,
"sunset": 1476292372
},
"id": 2643743,
"name": "London",
"cod": 200
}'''
def result = new JsonSlurper().parseText(json)
log.info(result)
assert result.weather.main == "Clouds"
Upvotes: 0
Views: 2152
Reputation: 21389
Looks it's a trivial issue.
weather
is an array(in []) and that is why the assertion fails.
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
If you do result.weather.main
, then it returns a list which contains an element Clouds
. But,not a single value as you expected.
So, you can do:
assert result.weather[0].main == 'Clouds', 'Not matching the expected result'
or
assert result.weather.main == ['Clouds']
or
assert result.weather.main.contains('Clouds')
For suppose if weather is below (example with more elements in json array):
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
},
{
"id": 802,
"main": "CloudApps",
"description": "few clouds",
"icon": "03n"
}
],
Then assertion can be done
assert result.weather.main == ['Clouds', 'CloudApps']
Upvotes: 0
Reputation: 3026
weather in your json is array. You can access it elements as a regular array
assert result.weather.main[0] == "Clouds"
assert result?.weather?.main?.getAt(0) == "Clouds"
second prefered because it null safe
Upvotes: 0
Reputation: 635
Weather is an array of maps, as I see. So, you need to select an item or groovy will return to you an array of main.
assert result.weather.first().main == "Clouds"
assert result.weather.main == ["Clouds"]
Upvotes: 0