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 on windows. I am getting below error message
TypeError: byte indices must be integers or slices, not str
#Parse response
jsonResponse = json.loads(response.content)
deviceID=(jsonResponse['data']['id'])
print('ID', str(deviceID))
Rahamath
Posted 7 years ago·Last reply 7 years ago
3 comments
Joe_Tran
·7 years agoCORRECTION to my last post. You'll want to iterate through 'items' list which is in the 'data' JSON-object.
Joe_Tran
·7 years agoA 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'
Mike Moniz
·7 years agoI don't really know python much but LM did state they will be providing a new Python SDK once v.113 is released (end of the month) which might make querying LM easier: https://www.logicmonitor.com/release-notes/v-113-release-notes/ . I haven't seen it myself.
Otherwise you may want to output/dump jsonResponse to make sure it's valid json (and not an http 501 error for example) or perhaps comment out the print line to see which line is causing the error? Perhaps you need to do ['data'][0]['id'] or the like? The API can return multiple devices. Again I don't really know python and I'm not currently setup to test with it.