Maz Maz - 1 year ago 84
reST (reStructuredText) Question

Unable to parse JSON that contains upper case key in Groovy

I'm attempting to parse JSON from a REST API and am unable to access the data when the key to that data is in uppercase format.

{
"body": {
"devices": [{
"_id": "xxxxxxxxxx",
"cipher_id": "xxxxxxxx",
"last_status_store": 1502808369,
"modules": [{
"_id": "xxxxxxx",
"type": "xxxxxxx",
"last_message": 1502808365,
"last_seen": 1502808359,
"dashboard_data": {
"time_utc": 1502808359,
"Temperature": 18.9,
"temp_trend": "down",
"Humidity": 27,
"date_max_temp": 1502804720,
"date_min_temp": 1502808359,
"min_temp": 18.9,
"max_temp": 22.2
},
"data_type": [
"Temperature",
"Humidity"
],
"last_setup": 1502731328,
"battery_vp": 6354,
"battery_percent": 100,
"rf_status": 67,
"firmware": 44
}],
"place": {
"altitude": 63.395306309052,
"city": "xxxxxx",
"country": "US",
"timezone": "America/New_York",
"location": [-72.532673,
42.0425917
]
},
"station_name": "xxxxxxxxxxx",
"type": "NAMain",
"dashboard_data": {
"AbsolutePressure": 1004.6,
"time_utc": 1502808354,
"Noise": 50,
"Temperature": 22.7,
"temp_trend": "up",
"Humidity": 69,
"Pressure": 1012.1,
"pressure_trend": "stable",
"CO2": 0,
"date_max_temp": 1502808290,
"date_min_temp": 1502801263,
"min_temp": 21.3,
"max_temp": 22.7
},
"data_type": [
"Temperature",
"CO2",
"Humidity",
"Noise",
"Pressure"
],
"co2_calibrating": false,
"date_setup": 1502731277,
"last_setup": 1502731277,
"module_name": "Indoor",
"firmware": 132,
"last_upgrade": 1502731279,
"wifi_status": 51
}]
},
"status": "ok",
"time_exec": 0.019752025604248,
"time_server": 1502808443
}


I am trying to access the JSON using a Groovy Json slurper and executing the following command. The response comes back fine in my debugger.Reponse.content is value of the HTTPrequest that i sent to the server.

def stationInfo = jsonSlurper.parseText(response.content as String)
def outsideTemp = stationInfo.body.devices.modules.dashboard_data.Temperture
def outsideHumidty = stationInfo.body.devices.modules.dashboard_data.Humidty
def insideTemp = stationInfo.body.devices.dashboard_data.Temperture


outsideTemp,outsideHumidty, and insideTemp are all eqaull to "[null]" when i view them in my debugger. Any ideas on why this is happening, and how to fix it? Is the compiler assuming something because these are uppercase?

Rao Rao
Answer Source

Looks are you almost there.

Note that, the json you have attached does not seem to be valid, fixed to be able to work.

def pJson = new groovy.json.JsonSlurper().parseText(response.content as String)
println pJson.body.devices.modules.dashboard_data.Temperature.flatten()
println pJson.body.devices.dashboard_data.Temperature.flatten()

Similar to Temparature, you can get it work for Humidity as well.

You can see the same in the demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download