gpt4 book ai didi

python JSON 到 dict 检查是否是单个或多个 child

转载 作者:行者123 更新时间:2023-12-01 03:51:15 24 4
gpt4 key购买 nike

我正在使用 python2.7 并动态接收需要解析的 JSON 字符串。

生成的字典如下所示”

{
u'queueId': u'channel.presence'
u'name': u'presence.message'
u'timestamp': 1467756404358
u'webhookId': u'U3P3Xw'
u'serial': u'e7da73f968767379:37'
u'data': {<br/>
u'channelId': u'private-cc-259970d91ab44af38393130e95de7057'
u'site': u'eu-central-1-A'
u'presence': {<br/>
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': {<br/>
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'
}
]
}
},

正如您从示例数据中看到的,[数据][存在]可以只有一个对象或多个对象。

我的测试完全失败,但有一个异常(exception):

Error: list indices must be integers, not str

我的代码:
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']:
...

不幸的是支票len(ji['data']['presence']) > 1当只有一项时也是如此。在这种情况下ch变为“操作”而不是子项。

如何检查字典中是否存在单个或多个项目?

最佳答案

您可以使用isinstance()确定该项目是否是列表:

presence = ji['data']['presence']
if isinstance(presence, list):
# ...

不过,如果我理解正确的话,这就是您正在寻找的逻辑:

presence = ji['data']['presence']
if isinstance(presence, dict): # or: if not isinstance(presence, list):
presence = [presence]

for ch in presence:
# ...

关于python JSON 到 dict 检查是否是单个或多个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38214224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com