簡體   English   中英

如何在 Python 3.x 中循環遍歷復雜的 JSON

[英]How to loop through complex JSON in Python 3.x

目前,我正在為我的家構建一個儀表板,從 Honeywell API 獲取溫度值。 我正在嘗試遍歷從 API 獲得的復雜 JSON 以獲取所有設備當前溫度。

由於我對 Python 很陌生,我不知道如何進行排序。 這是一個示例響應:

[
    {
        "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
    }
]

這里有誰知道如何獲取設備數組中的每個設備thermostat.indoortemperaturethermostat.changeableValues.HeatSetpoint.Value

看起來你有一個包含一本大字典的列表。 該字典有一個devices鍵值對,其中值是一個字典列表,每個設備一個。 如果data是您的 JSON 結構,您可以通過以下方式遍歷設備字典:

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))

這是一個 json 數組.. 將其轉換為字典數組,然后循環遍歷它並使用其對應的鍵從每個字典中獲取值。

import json

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

正如評論中提到的,這是一個包含字典元素的列表。

保存列表,我另存a (確保真/假為真/假)

對於每個位置,該列表的長度為 1。

選擇列表的第一個元素

a[0]

該列表包含一個字典,因此請打開字典以獲取所需的值devices 導航元素就像在您的計算機上導航文件結構

a[0]['devices']

這為您提供了一個包含三個字典的列表

遍歷字典。 參考thermostat子字典並選擇indoorTemperature

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

這為您提供了每個設備的“室內溫度”

我不知道你想要什么 output,但你可以使用這個邏輯來得到你需要的東西!

一般來說,獲取列表的值表示索引(例如a[0] ),獲取字典的值表示鍵(例如 device['thermostat'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM