handling objects in json parsing using python

Maheshwaram Srikaran 96 Reputation points
2022-02-02T12:33:19.383+00:00

I am receiving the device status from iot hub. Response is similar to this

properties: {  
    desired: {  
      Hello: '67',  
      Hey: 1,  
      power_level: 1,  
      '$metadata': [Object],  
      '$version': 27  
    }      
     reported: {  
      check: [Object],  
      try: [Object],  
      '$metadata': [Object],  
      '$version': 10  
    }  
  }  

Since it doesn't seem to be valid, as object comes in key's value. Unable to get the entire packet response over python language.

Using javascript, able to parse data by following way:
res.properties.desired

Is there a similar way in python to parse and get the entire packet ?

Followed this docs, to get the response from the IOT Hub
<https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-python-twin-getstarted>

iothub_registry_manager = IoTHubRegistryManager(IOTHUB_CONNECTION_STRING)  
 twin = iothub_registry_manager.get_twin(DEVICE_ID)
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,112 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sander van de Velde 28,236 Reputation points MVP
    2022-02-02T18:11:46.077+00:00

    Hello @Maheshwaram Srikaran ,

    you want to access the device twin on a device in the Azure IoT Hub.

    There are several samples available on GitHub accessing the device twin, mostly about patching the desired properties.

    But to show how to access individual desired properties (and reported properties also) I tweaked this sample.

    Here I access the twin:

    # Create IoTHubRegistryManager  
    registry_manager = IoTHubRegistryManager(CONNECTION_STRING)  
      
    twin = registry_manager.get_twin(DEVICE_ID)  
      
    print ( "Twin device id:" )  
    print ( twin.device_id )  
    print("Twin desired properties document:")  
    print("{}".format(twin.properties.desired))  
    print("Twin desired properties key and value:")  
    for key, value in twin.properties.desired.items():  
        print (key, value)  
      
    print("Twin reported properties key and value:")  
    for key, value in twin.properties.reported.items():  
        print (key, value)  
    

    The device twin of my device looks like this:

    170636-image.png

    To run the code, I have to install this PIP package:

    pip install azure.iot.hub  
    

    This is the result when I run the code:

    170650-image.png

    As you can see, I can access both desired and reported properties.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful