fambo fambo - 1 month ago 7
Groovy Question

How to extract JSON parameter using JsonSlurper in Groovy

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"

Answer

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"​]​
Comments