【问题标题】:Error when trying to get len() from json object尝试从 json 对象获取 len() 时出错
【发布时间】: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


【解决方案1】:

有些物品没有traitIds,所以你需要处理这种情况。

import requests

url = 'https://www.bungie.net/common/destiny2_content/json/en/DestinyInventoryItemDefinition-33183ba8-e1c4-4364-8827-dbdcf46315dd.json'
resp = requests.get(url)
data = resp.json()

for key, value in data.items():
    trait_ids = value.get('traitIds') # this will yield None if traitIds key is missing
    if trait_ids and 'item_type.weapon' in trait_ids:
        print(value['displayProperties']['name']) # you may want to use .get() also here to avoid possible KeyError.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2022-01-13
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2023-04-09
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多