Issues with turning json data into an variable in python

405 Views Asked by At

I have been working on an educational project a small part of it requires me to convert a single line of json data into an variable in python 3 which I recieve from domoticz (an external open source software) however due to my skill level with json I have expierenced some issues and I am not exactly sure what im doing wrong. I did get the 200 response everytime so I assume from what I understood that means the connection isnt the issue but rather the python code. (I censored the addressed but they are correct.)

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)

The json I get back which i can see by typing clicking the url in python:

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

Basicly I want SetPoint(in the last tab of text also right above this) which is in this instance 17.5 as a variable in python and I will make the python code loop so it will grab that json url everytime to update the status of setpoint. But im having issues only grabbing the 17.5 to make it into a variable. I end up getting the entire json like this code is doing. or I will end up getting everything past and including the setpoint if I change some stuff. Does anyone know what im doing wrong and possibly where I should be looking for an solution? I am a bit unexpierenced with the json part of python and I have no clue where to get started as the code's I found and have tried seem to not work or give me errors. Thank you very much for your time!

2

There are 2 best solutions below

0
On BEST ANSWER

You are getting your data stored in data ={"key": argument} as a dictionary. If you want to access a certain value you have to call for it. in Your case:

SetPoint = float(data["result"][-1]["SetPoint"])

To break it down:

data["result"] # gives you a list which elements are dictionaries.
the [-1] # calls for the last element in you list which contains the SetPoint
["SetPoint"] # then calls for the SetPoint Value which is a String "17.5"
float(...) converts the string to a float value
0
On

json.loads returns a python dictionary so maybe sth like this would do:

result = json['result']
set_point = 0.0 

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