'Error when trying to get len() from json object
When I'm trying to get the length of a json object I'm getting the following error:size = len(response_info[weapon]['traitIds']) KeyError: 'traitIds'
I get no error when removing the len() and the object is looks like the following:traitIds:['value1', 'value2']
Do you know how I can fix this?
I'm using the following json file: https://www.bungie.net/common/destiny2_content/json/en/DestinyInventoryItemDefinition-33183ba8-e1c4-4364-8827-dbdcf46315dd.json
Code Sample:
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
Solution 1:[1]
there are items without traitIds, so you need to handle this case.
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
