7 years ago
parsing response
Hello All,
I need some help on the python 3. I am getting device information in response.content. I need to display only id from it. How to parse the response.content. I am using Python 3.5 o...
A couple things.
If you are using the requests Python package, you can use the .json() method from the response class. The .content property will return bytes, and that just makes things more complicated than necessary.
Assuming this is v1 REST API (because you are referencing the 'data' key from the response), is your API call hitting the /device/devices/{devId} or is it /device/devices resource path (i.e. are you GET'ing a specific device by id or a list of devices)?
A GET for /device/devices should return a <class 'list'> object for the 'data' key or, as @Mike Moniz mentioned, will return 0 to n number of devices.
So either iterate through all the devices in 'data' or if you only care about the first device, reference the 0 index of 'data'
import requests [...] # use .json() method instead of .content jsonResponse = response.json() # Iterate through all devices in 'data' for device in jsonResponse['data']: deviceID = device['id'] print('ID', str(deviceID)) # Only care about the first device in 'data' deviceID=(jsonResponse['data'][0]['id']) print('ID', str(deviceID))