Page 1 of 1

Fetching Data in Python throw JSON

Posted: 15 May 2018 15:39
by billyboy
For my project I needed to fetch z-wave location and device info and fill structs with this data.
I have writen python code to do this and want to share it with you. Use it if you like.

Code: Select all

import json
import requests

topLevelUrl = ''
DevicesUrl= topLevelUrl +'/ZAutomation/api/v1/devices'
LocationsUrl= topLevelUrl +'/ZAutomation/api/v1/locations'
LoginUrl = topLevelUrl + '/ZAutomation/api/v1/login'
username = 'YourUserName'
password = 'YourPassword'
LoginHeader = {'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/json'}
Formlogin = '{"form": true, "login": "'+username+'", "password": "'+password+'", "keepme": false, "default_ui": 1}'

session = requests.Session(),headers=LoginHeader, data=Formlogin)

Locations = []
Devices = []

class DeviceDescription:
  def __init__(self, **kwargs):
    self.deviceId = None
    self.deviceName = None
    for key, value in kwargs.iteritems():
      if   key == 'deviceId':   self.deviceId = value
      elif key == 'deviceName': self.deviceName = value
#end class DeviceDescription

class DeviceGroup:
  def __init__(self, **kwargs): = None
    self.devices = []
    for key, value in kwargs.iteritems():
      if   key == 'id': = value
      elif key == 'params':
        jsonObj = json.loads(value)
        for dev in jsonObj:
          if 'deviceId' in dev and 'deviceName' in dev:
            self.devices.append(DeviceDescription(deviceId = dev['deviceId'], deviceName = dev['deviceName']))
#end class DeviceGroupDescription

class Location:
  def __init__(self, **kwargs): = None
    self.title = None
    self.user_img = None
    self.default_img = None
    self.img_type = None
    self.deviceGroups = []
    for key, value in kwargs.iteritems():
      if   key == 'id':  = value
      elif key == 'title':        self.title = value
      elif key == 'user_img':     self.user_img = value
      elif key == 'default_img':  self.default_img = value
      elif key == 'img_type':     self.img_type = value
      elif key == 'namespaces':
        jsonObj = json.loads(value)
        for devGrp in jsonObj:
          self.deviceGroups.append(DeviceGroup(id = devGrp['id'], params = json.dumps(devGrp['params'])))
#end class Location

def FetchLocations():
  global Locations
  response = session.get(LocationsUrl)
  html = response.text
  #print html
    parsed_json = response.json()
    if 'code' in parsed_json:
      code = parsed_json['code']
      if code != 200:
        print('Fetch Location error: {0}'.format(code))
        if 'data' in parsed_json:
          data = parsed_json['data']  #array with Locations
          del Locations[:]
          for i, val in enumerate(data):	#walk through all received Locations
            urlLocation = data[i]
            Locations.append(Location(id       = urlLocation['id'],\
                                      title    = urlLocation['title'],\
                                      user_img = urlLocation['user_img'],\
                                      default_img = urlLocation['default_img'],\
                                      img_type = urlLocation['img_type'],\
                                      namespaces = json.dumps(urlLocation['namespaces'])
  except ValueError, e:
    print("Invalid Google Docs JSON configuration in %s' % (e)")
#end def FetchLocations
def PrintLocations():
  for i, loc in enumerate(Locations):
    print('id={0} Room="{1}"'.format(, loc.title))
    for j, devGrp in enumerate(loc.deviceGroups):
      print('\tgroup = {0}'.format(
      for k, dev in enumerate(devGrp.devices):
        print('\t\tdeviceId="{0}", Name="{1}"'.format(dev.deviceId, dev.deviceName))
#end def PrintLocations

class Order:
  def __init__(self, **kwargs):
    self.rooms = None
    self.elements = None
    self.dashboard = None
    for key, value in kwargs.iteritems():
      if   key == 'rooms':   self.rooms = value
      elif key == 'elements': self.elements = value
      elif key == 'dashboard': self.dashboard = value
#end Order

class Metrics:
  def __init__(self, **kwargs):
    self.title = None
    self.level = None
    self.lastLevel = None
    self.mode = None
    self.icon = None
    self.scaleTitle = None
    self.probeTitle = None
    self.modificationTime = None
    self.isFailed = None
#end class Metrics    

class Device:
  def __init__(self, **kwargs): = None
    self.location = None
    self.metrics = Metrics()
    self.lastLevel = None
    self.creationTime = None
    self.creatorId = None
    self.customIcons = []  
    self.deviceType = None
    self.h = None
    self.hasHistory = None
    self.order = Order()
    self.permanently_hidden = None
    self.probeType = None
    self.tags = []
    self.visibility = None
    self.updateTime = None
    for key, value in kwargs.iteritems():
      if   key == 'id': = value
      elif key == 'location': self.location = value
      elif key == 'metrics': self.metrics = value
      elif key == 'title': self.title = value
      elif key == 'level': self.level = value
      elif key == 'lastLevel': self.lastLevel = value
      elif key == 'mode': self.mode = value
      elif key == 'creationTime':   self.creationTime = value
      elif key == 'creatorId': self.creatorId = value
      elif key == 'customIcons': 
        for i, icon in enumerate(value):
      elif key == 'deviceType': self.deviceType = value
      elif key == 'h': self.h = value
      elif key == 'hasHistory': self.hasHistory = value
      elif key == 'icon': self.icon = value
      elif key == 'order': self.order = value
      elif key == 'permanently_hidden': self.permanently_hidden = value
      elif key == 'probeType': self.probeType = value
      elif key == 'tags':
        for i, tag in enumerate(value):
      elif key == 'visibility': self.visibility = value
      elif key == 'updateTime': self.updateTime = value
#end class Device

def FetchDevices():
  global Devices
  response = session.get(DevicesUrl)
  html = response.text
  #print html
    parsed_json = response.json()
    if 'code' in parsed_json:
      code = parsed_json['code']
      if code != 200:
        print('Fetch devices from z-wave server!')
        if 'data' in parsed_json:
          data = parsed_json['data']
          if 'devices' in data:
            urlDevices = data['devices']			#array with devices
            for i, dev in enumerate(urlDevices):	#walk through all received devices
              if 'id' in urlDevices[i]:
                urlDevice = urlDevices[i]
                dev = Device(id = urlDevice['id'])
                if 'metrics' in urlDevice:
                  urlMetrics = urlDevice['metrics']
                  if 'title' in urlMetrics:
                    dev.metrics.title = urlMetrics['title']
                  if 'level' in urlMetrics:
                    dev.metrics.level = urlMetrics['level']
                  if 'lastLevel' in urlMetrics:
                    dev.metrics.lastLevel = urlMetrics['lastLevel']
                  if 'mode' in urlMetrics:
                    dev.metrics.mode = urlMetrics['mode']
                  if 'icon' in urlMetrics:
                    dev.metrics.icon = urlMetrics['icon']
                  if 'scaleTitle' in urlMetrics:
                    dev.metrics.scaleTitle = urlMetrics['scaleTitle']
                  if 'probeTitle' in urlMetrics:
                    dev.metrics.probeTitle = urlMetrics['probeTitle']
                  if 'modificationTime' in urlMetrics:
                    dev.metrics.modificationTime = urlMetrics['modificationTime']
                  if 'isFailed' in urlMetrics:
                    dev.metrics.isFailed = urlMetrics['isFailed']
                if 'creationTime' in urlDevice:
                  dev.creationTime = urlDevice['creationTime']
                if 'creatorId' in urlDevice:
                  dev.creatorId = urlDevice['creatorId']
                if 'customIcons' in urlDevice:
                  dev.customIcons = urlDevice['customIcons']
                if 'deviceType' in urlDevice:
                  dev.deviceType = urlDevice['deviceType']
                if 'h' in urlDevice:
                  dev.h = urlDevice['h']
                if 'hasHistory' in urlDevice:
                  dev.hasHistory = urlDevice['hasHistory']
                if 'order' in urlDevice:
                  urlOrder = urlDevice['order']
                  if 'rooms' in urlOrder:
                    dev.order.rooms = urlOrder['rooms']
                  if 'elements' in urlOrder:
                    dev.order.elements = urlOrder['elements']
                  if 'dashboard' in urlOrder:
                    dev.order.dashboard = urlOrder['dashboard']
                if 'permanently_hidden' in urlDevice:
                  dev.permanently_hidden = urlDevice['permanently_hidden']
                if 'probeType' in urlDevice:
                  dev.probeType = urlDevice['probeType']
                if 'tags' in urlDevice:
                  dev.tags = urlDevice['tags']
                if 'visibility' in urlDevice:
                  dev.visibility = urlDevice['visibility']
                if 'updateTime' in urlDevice:
                  dev.updateTime = urlDevice['updateTime']
  except ValueError, e:
    print("Invalid Google Docs JSON configuration in %s' % (e)")
#end  def FetchDevices
def PrintDevices():
  for i, dev in enumerate(Devices):
    print('Device id="{0}", location={1}'.format(, dev.location))
    print('\tMetrics: title="{0}", level={1}, lastLevel={2}, mode={3},\n\t\t icon={4}, scaleTitle={5}, probeTitle={6}, modificationTime={7}, isFailed={8}'.format(dev.metrics.title,\
#end def PrintDevices

print('-= Locations =-')        
print('-= Devices =-')        

Have fun!