Reputation: 1590
I am using python2.7 and receive dynamically a JSON string that I need to parse.
The resulting dict looks as follows"
{
u'queueId': u'channel.presence'
u'name': u'presence.message'
u'timestamp': 1467756404358
u'webhookId': u'U3P3Xw'
u'serial': u'e7da73f968767379:37'
u'data': {
u'channelId': u'private-cc-259970d91ab44af38393130e95de7057'
u'site': u'eu-central-1-A'
u'presence': {
u'action': u'enter'
u'connectionId': u'LA84hfOd_w'
u'data': u'a012a914cce6096c4a02a29da51dbc58'
u'clientId': u'a012a914cce6096c4a02a29da51dbc58'
}
}
},
{
u'queueId': u'channel.presence'
u'name': u'presence.message'
u'timestamp': 1467756452665
u'webhookId': u'U3P3Xw'
u'serial': u'e7da73f968767379:40'
u'data': {
u'channelId': u'private-a012a914cce6096c4a02a29da51dbc58'
u'site': u'eu-central-1-A'
u'presence': [
{
u'timestamp': 1467756404550
u'connectionId': u'LA84hfOd_w'
u'clientId': u'a012a914cce6096c4a02a29da51dbc58'
u'action': 3
u'data': u'a012a914cce6096c4a02a29da51dbc58'
u'id': u'LA84hfOd_w-2:0'
}
]
}
},
As you can see from the example data the [data][presence] can have either just a single object or multiple objects.
My testing for that fails utterly with the exception:
Error: list indices must be integers, not str
My code:
for ji in json_data['items']:
channel_id = ji['data']['channelId']
logger.debug("ChannelID: %s" % channel_id)
found_special_case = False
if len(ji['data']['presence']) > 1 :
for ch in ji['data']['presence']:
...
Unfortunatly the check len(ji['data']['presence']) > 1
is also true when there is only one item. In that case ch
becomes 'action' instead of the child item.
How can I check whether there is a single or several items in a dictionary?
Upvotes: 1
Views: 2366
Reputation: 473863
You can use isinstance()
to determine if the item is a list or not:
presence = ji['data']['presence']
if isinstance(presence, list):
# ...
Though, if I understand you correctly, this is the logic you are looking for:
presence = ji['data']['presence']
if isinstance(presence, dict): # or: if not isinstance(presence, list):
presence = [presence]
for ch in presence:
# ...
Upvotes: 4