首页 > 解决方案 > 在 python 中将 json 数据转换为变量的问题

问题描述

我一直在从事一个教育项目,其中一小部分需要我将单行 json 数据转换为 python 3 中的一个变量,我从 domoticz(一个外部开源软件)收到该变量,但是由于我的 json 技能水平我遇到了一些问题,我不确定我做错了什么。我确实每次都收到 200 响应,所以我假设根据我的理解,这意味着连接不是问题,而是 python 代码。(我审查了地址,但它们是正确的。)

The code im using:
import time
import re
import requests
from ctypes import c_int, c_char_p, byref, sizeof, c_uint16, c_int32, c_byte
from ctypes import c_void_p
from datetime import datetime
import os
import urllib.request
import json
import logging
import sys
from requests.exceptions import HTTPError
logger = logging.getLogger(__name__)
domoticzserver='ip'
switchid='3'
device='5'
tempbed=str(4)
def domoticzrequest (url):
  request = urllib.request.Request(url)
  response = urllib.request.urlopen(request)
  return response.read()
import urllib.request, json 
with urllib.request.urlopen("http://domoticzip/json.htm?type=devices&rid=4") as url:
data = json.loads(url.read().decode())
    print(data)

我得到的 json 我可以通过在 python 中键入单击 url 来查看:

{
    "ActTime" : 1606722346,
    "AstrTwilightEnd" : "18:37",
    "AstrTwilightStart" : "06:23",
    "CivTwilightEnd" : "17:14",
    "CivTwilightStart" : "07:47",
    "DayLength" : "08:08",
    "NautTwilightEnd" : "17:56",
    "NautTwilightStart" : "07:04",
    "ServerTime" : "2020-11-30 08:45:46",
    "SunAtSouth" : "12:30",
    "Sunrise" : "08:26",
    "Sunset" : "16:34",
    "app_version" : "2020.2",
    "result" : 
    [
        {
            "AddjMulti" : 1.0,
            "AddjMulti2" : 1.0,
            "AddjValue" : 0.0,
            "AddjValue2" : 0.0,
            "BatteryLevel" : 255,
            "CustomImage" : 0,
            "Data" : "Normal",
            "Description" : "",
            "Favorite" : 0,
            "HardwareID" : 1,
            "HardwareName" : "Domoticz Internal",
            "HardwareType" : "Domoticz Internal interface",
            "HardwareTypeVal" : 67,
            "HaveDimmer" : false,
            "HaveGroupCmd" : false,
            "HaveTimeout" : false,
            "ID" : "148702",
            "LastUpdate" : "2020-10-19 15:10:02",
            "MaxDimLevel" : 0,
            "Name" : "Domoticz Security Panel",
            "Notifications" : "false",
            "PlanID" : "0",
            "PlanIDs" : 
            [
                0
            ],
            "Protected" : false,
            "ShowNotifications" : true,
            "SignalLevel" : "-",
            "Status" : "Normal",
            "StrParam1" : "",
            "StrParam2" : "",
            "SubType" : "Security Panel",
            "SwitchType" : "Security",
            "SwitchTypeVal" : 0,
            "Timers" : "false",
            "Type" : "Security",
            "TypeImg" : "security",
            "Unit" : 0,
            "Used" : 0,
            "XOffset" : "0",
            "YOffset" : "0",
            "idx" : "2"
        },
        {
            "AddjMulti" : 1.0,
            "AddjMulti2" : 1.0,
            "AddjValue" : 0.0,
            "AddjValue2" : 0.0,
            "BatteryLevel" : 255,
            "CustomImage" : 0,
            "Data" : "-5.0 C",
            "Description" : "",
            "Favorite" : 1,
            "HardwareID" : 2,
            "HardwareName" : "Test sensor",
            "HardwareType" : "Dummy (Does nothing, use for virtual switches only)",
            "HardwareTypeVal" : 15,
            "HaveTimeout" : true,
            "ID" : "14053",
            "LastUpdate" : "2020-11-09 09:03:34",
            "Name" : "Temperatuur Kachel",
            "Notifications" : "false",
            "PlanID" : "0",
            "PlanIDs" : 
            [
                0
            ],
            "Protected" : false,
            "ShowNotifications" : true,
            "SignalLevel" : "-",
            "SubType" : "LaCrosse TX3",
            "Temp" : -5.0,
            "Timers" : "false",
            "Type" : "Temp",
            "TypeImg" : "temperature",
            "Unit" : 1,
            "Used" : 1,
            "XOffset" : "0",
            "YOffset" : "0",
            "idx" : "3",
            "trend" : 0
        },
        {
            "AddjMulti" : 1.0,
            "AddjMulti2" : 1.0,
            "AddjValue" : 0.0,
            "AddjValue2" : 0.0,
            "BatteryLevel" : 255,
            "CustomImage" : 0,
            "Data" : "17.5",
            "Description" : "",
            "Favorite" : 1,
            "HardwareID" : 3,
            "HardwareName" : "Test switch",
            "HardwareType" : "Dummy (Does nothing, use for virtual switches only)",
            "HardwareTypeVal" : 15,
            "HaveTimeout" : true,
            "ID" : "0014054",
            "LastUpdate" : "2020-11-06 11:51:09",
            "Name" : "Temperatuur gewenst",
            "Notifications" : "false",
            "PlanID" : "0",
            "PlanIDs" : 
            [
                0
            ],
            "Protected" : false,
            "SetPoint" : "17.5",
            "ShowNotifications" : true,
            "SignalLevel" : "-",
            "SubType" : "SetPoint",
            "Timers" : "false",
            "Type" : "Thermostat",
            "TypeImg" : "override_mini",
            "Unit" : 1,
            "Used" : 1,
            "XOffset" : "0",
            "YOffset" : "0",
            "idx" : "4"
        }
    ],
    "status" : "OK",
    "title" : "Devices"
}

基本上我想要SetPoint(在文本的最后一个选项卡中),在这个实例中是17.5作为python中的一个变量,我将让python代码循环,所以它每次都会抓取那个json url来更新设置点的状态。但我有问题只能抓住 17.5 使其成为一个变量。我最终像这段代码一样得到了整个 json。或者如果我改变一些东西,我最终会得到所有的东西,包括设定点。有谁知道我做错了什么以及我应该在哪里寻找解决方案?我对 python 的 json 部分有点缺乏经验,我不知道从哪里开始,因为我发现并尝试过的代码似乎不起作用或给我错误。非常感谢您的宝贵时间!

标签: pythondomoticz

解决方案


json.loads 返回一个 python 字典,所以也许这样的事情会做:

result = json['result']
set_point = 0.0 

for res in result:
   if 'SetPoint' in res:
        set_point = res['SetPoint']

推荐阅读