【发布时间】:2022-01-25 06:53:06
【问题描述】:
当我尝试获取 json 对象的长度时,出现以下错误:size = len(response_info[weapon]['traitIds']) KeyError: 'traitIds'
删除 len() 时我没有收到任何错误,对象如下所示:traitIds:['value1', 'value2']
你知道我该如何解决这个问题吗?
我正在使用以下 json 文件:https://www.bungie.net/common/destiny2_content/json/en/DestinyInventoryItemDefinition-33183ba8-e1c4-4364-8827-dbdcf46315dd.json
代码示例:
for weapon in response_info:
size = len(response_info[weapon]['traitIds'])
if (i <= i):
while x <= size:
try:
if (response_info[weapon]['traitIds'][x] == 'item_type.weapon'):
print(response_info[weapon]['displayProperties']['name'])
i += 1
print(size)
except:
pass
x += 1
【问题讨论】:
-
weapon是变量还是键?你能分享这段 2-4 行的代码吗? -
请检查How to Ask。发布minimal reproducible example,包括。您的 JSON 样本。
-
请包含您的 JSON 文件示例。
-
@KrishnakanthAllika 我做到了。
标签: python json python-3.x