Home > Blockchain >  How to loop through complex JSON in Python 3.x
How to loop through complex JSON in Python 3.x

Time:01-04

Currently, I'm building a dashboard for my home where I get temperature values from the Honeywell API. I'm trying to loop through a complex JSON that I got from the API to get all the device current temperatures.

Since I'm quite new to Python I have no clue how to get this sorted. Here is an example response:

[
    {
        "locationID": 5018081,
        "type": "Residential",
        "hasStation": true,
        "devices": [
            {
                "gatewayId": 4773548,
                "deviceID": 6575395,
                "thermostatModelType": "EMEA_ZONE",
                "deviceType": 128,
                "name": "Badkamer 1e",
                "scheduleCapable": false,
                "holdUntilCapable": false,
                "thermostat": {
                    "units": "Celsius",
                    "indoorTemperature": 18.8300,
                    "outdoorTemperature": 128.0000,
                    "outdoorTemperatureAvailable": false,
                    "outdoorHumidity": 128.0000,
                    "outdootHumidityAvailable": false,
                    "indoorHumidity": 128.0000,
                    "indoorTemperatureStatus": "Measured",
                    "indoorHumidityStatus": "NotAvailable",
                    "outdoorTemperatureStatus": "NotAvailable",
                    "outdoorHumidityStatus": "NotAvailable",
                    "isCommercial": false,
                    "allowedModes": [
                        "Heat",
                        "Off"
                    ],
                    "deadband": 0.0000,
                    "minHeatSetpoint": 5.0000,
                    "maxHeatSetpoint": 35.0000,
                    "minCoolSetpoint": 50.0000,
                    "maxCoolSetpoint": 90.0000,
                    "changeableValues": {
                        "mode": "Off",
                        "heatSetpoint": {
                            "value": 19.0,
                            "status": "Scheduled"
                        },
                        "vacationHoldDays": 0
                    },
                    "scheduleCapable": false,
                    "vacationHoldChangeable": false,
                    "vacationHoldCancelable": false,
                    "scheduleHeatSp": 0.0000,
                    "scheduleCoolSp": 0.0000
                },
                "alertSettings": {
                    "deviceID": 6575395,
                    "tempHigherThanActive": true,
                    "tempHigherThan": 30.0000,
                    "tempHigherThanMinutes": 0,
                    "tempLowerThanActive": true,
                    "tempLowerThan": 5.0000,
                    "tempLowerThanMinutes": 0,
                    "faultConditionExistsActive": false,
                    "faultConditionExistsHours": 0,
                    "normalConditionsActive": true,
                    "communicationLostActive": false,
                    "communicationLostHours": 0,
                    "communicationFailureActive": true,
                    "communicationFailureMinutes": 15,
                    "deviceLostActive": false,
                    "deviceLostHours": 0
                },
                "isUpgrading": false,
                "isAlive": true,
                "thermostatVersion": "02.00.17.00",
                "macID": "B82CA0CCEB90",
                "locationID": 5018081,
                "domainID": 60304,
                "instance": 9
            },
            {
                "gatewayId": 4773548,
                "deviceID": 6575388,
                "thermostatModelType": "EMEA_ZONE",
                "deviceType": 128,
                "name": "Badkamer BG",
                "scheduleCapable": false,
                "holdUntilCapable": false,
                "thermostat": {
                    "units": "Celsius",
                    "indoorTemperature": 20.3200,
                    "outdoorTemperature": 128.0000,
                    "outdoorTemperatureAvailable": false,
                    "outdoorHumidity": 128.0000,
                    "outdootHumidityAvailable": false,
                    "indoorHumidity": 128.0000,
                    "indoorTemperatureStatus": "Measured",
                    "indoorHumidityStatus": "NotAvailable",
                    "outdoorTemperatureStatus": "NotAvailable",
                    "outdoorHumidityStatus": "NotAvailable",
                    "isCommercial": false,
                    "allowedModes": [
                        "Heat",
                        "Off"
                    ],
                    "deadband": 0.0000,
                    "minHeatSetpoint": 5.0000,
                    "maxHeatSetpoint": 35.0000,
                    "minCoolSetpoint": 50.0000,
                    "maxCoolSetpoint": 90.0000,
                    "changeableValues": {
                        "mode": "Off",
                        "heatSetpoint": {
                            "value": 19.0,
                            "status": "Scheduled"
                        },
                        "vacationHoldDays": 0
                    },
                    "scheduleCapable": false,
                    "vacationHoldChangeable": false,
                    "vacationHoldCancelable": false,
                    "scheduleHeatSp": 0.0000,
                    "scheduleCoolSp": 0.0000
                },
                "alertSettings": {
                    "deviceID": 6575388,
                    "tempHigherThanActive": true,
                    "tempHigherThan": 30.0000,
                    "tempHigherThanMinutes": 0,
                    "tempLowerThanActive": true,
                    "tempLowerThan": 5.0000,
                    "tempLowerThanMinutes": 0,
                    "faultConditionExistsActive": false,
                    "faultConditionExistsHours": 0,
                    "normalConditionsActive": true,
                    "communicationLostActive": false,
                    "communicationLostHours": 0,
                    "communicationFailureActive": true,
                    "communicationFailureMinutes": 15,
                    "deviceLostActive": false,
                    "deviceLostHours": 0
                },
                "isUpgrading": false,
                "isAlive": true,
                "thermostatVersion": "02.00.17.00",
                "macID": "B82CA0CCEB90",
                "locationID": 5018081,
                "domainID": 60304,
                "instance": 2
            },
            {
                "gatewayId": 4773548,
                "deviceID": 6575389,
                "thermostatModelType": "EMEA_ZONE",
                "deviceType": 128,
                "name": "Garage",
                "scheduleCapable": false,
                "holdUntilCapable": false,
                "thermostat": {
                    "units": "Celsius",
                    "indoorTemperature": 17.1600,
                    "outdoorTemperature": 128.0000,
                    "outdoorTemperatureAvailable": false,
                    "outdoorHumidity": 128.0000,
                    "outdootHumidityAvailable": false,
                    "indoorHumidity": 128.0000,
                    "indoorTemperatureStatus": "Measured",
                    "indoorHumidityStatus": "NotAvailable",
                    "outdoorTemperatureStatus": "NotAvailable",
                    "outdoorHumidityStatus": "NotAvailable",
                    "isCommercial": false,
                    "allowedModes": [
                        "Heat",
                        "Off"
                    ],
                    "deadband": 0.0000,
                    "minHeatSetpoint": 5.0000,
                    "maxHeatSetpoint": 35.0000,
                    "minCoolSetpoint": 50.0000,
                    "maxCoolSetpoint": 90.0000,
                    "changeableValues": {
                        "mode": "Off",
                        "heatSetpoint": {
                            "value": 17.0,
                            "status": "Scheduled"
                        },
                        "vacationHoldDays": 0
                    },
                    "scheduleCapable": false,
                    "vacationHoldChangeable": false,
                    "vacationHoldCancelable": false,
                    "scheduleHeatSp": 0.0000,
                    "scheduleCoolSp": 0.0000
                },
                "alertSettings": {
                    "deviceID": 6575389,
                    "tempHigherThanActive": true,
                    "tempHigherThan": 30.0000,
                    "tempHigherThanMinutes": 0,
                    "tempLowerThanActive": true,
                    "tempLowerThan": 5.0000,
                    "tempLowerThanMinutes": 0,
                    "faultConditionExistsActive": false,
                    "faultConditionExistsHours": 0,
                    "normalConditionsActive": true,
                    "communicationLostActive": false,
                    "communicationLostHours": 0,
                    "communicationFailureActive": true,
                    "communicationFailureMinutes": 15,
                    "deviceLostActive": false,
                    "deviceLostHours": 0
                },
                "isUpgrading": false,
                "isAlive": true,
                "thermostatVersion": "02.00.17.00",
                "macID": "B82CA0CCEB90",
                "locationID": 5018081,
                "domainID": 60304,
                "instance": 3
            }
        ],
        "oneTouchButtons": [],
        "weather": {
            "condition": "Cloudy",
            "temperature": 8.7,
            "units": "Celsius",
            "humidity": 91,
            "phrase": "Cloudy"
        },
        "daylightSavingTimeEnabled": true,
        "timeZone": {
            "id": "W. Europe Standard Time",
            "displayName": "(UTC 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",
            "offsetMinutes": 60,
            "currentOffsetMinutes": 60,
            "usingDaylightSavingTime": true
        },
        "oneTouchActionsSuspended": false,
        "isLocationOwner": true,
        "locationOwnerID": 4172939,
        "canSearchForContractors": true
    }
]

Does anyone here know how to get per device in the devices array the thermostat.indoortemperature and the thermostat.changeableValues.HeatSetpoint.Value?

CodePudding user response:

Looks like you've got a list containing one big dictionary. That dictionary has a devices key-value pair, where the value is a list of dictionaries, one for each device. If data is your JSON structure, you can iterate through the device-dictionaries in the following way:

data = ...

for device in data[0]["devices"]:
    indoor_temp = device["thermostat"]["indoorTemperature"]
    heat_set_point = device["changeableValues"]["heatSetpoint"]["value"]
    print("Device ID: {}".format(device["deviceID"]))
    print("Indoor temperature: {}".format(indoor_temp))
    print("Heat set point: {}\n".format(heat_set_point))

CodePudding user response:

This is a json array.. convert it to array of dictionaries then loop through it and get the values from each dictionary using its corresponding key.

import json

json_array_string = u'[{ "key":"value", ... }, {...}, ... ]'
array = json.loads(json_string)

CodePudding user response:

As mentioned in comments this is a list with elements that are dictionaries.

Save the list, I saved as a (make sure true/false are True/False)

The list has a length of one, for each location.

Choose the first element of the list

a[0]

The list contains a dictionary, so open the dictionary for the value you want devices. Navigating the elements is like navigating file structure on your compute

a[0]['devices']

This gives you a list with three dictionaries

Iterate through the dictionaries. Reference the thermostat sub-dictionary and choose the indoorTemperature key

[i['thermostat']['indoorTemperature'] for i in a[0]['devices']]

This gives you the `indoorTemperature' for each device

I dont know exactly what output you want, but you can use this logic to get what you need!

In general to get value of a list indicate the index (eg a[0]) to get the value of a dictionary indicate the key (eg device['thermostat'])

  •  Tags:  
  • Related