What I should to do, to avoid Keyerror
in my code, I'm a noob :)
I load json and print all the values from the array by tag status_name
, but the algorithm fails on an Keyerror
, how can I handle it and then save the resulting list to a file?
import json
with open(r'.json', encoding='utf-8') as fp:
data = json.load(fp)
for data in data:
print(data['status_name'])
I get data from all tags status_name
on request, but when the request reaches a tag where is no tag status_name
, I get:
Traceback (most recent call last):
line 6, in <module>
KeyError: 'status_name'
Print Output:
v
v
v
m
u
u
m
v
v
v
v
I want to print none or skip such blocks
There are two ways of handling the error:
Method 1
import json
with open(r'.json', encoding='utf-8') as fp:
data = json.load(fp)
new_data = []
for d in data: # use different variable name
# is d a dictionary and does it have 'status_name' as a key?
if isinstance(d, dict) and 'status_name' in d:
new_data.append(d)
"""
# the above loop can be reduced to the more "Pythonic" list comprehension:
new_data = [d for d in data if isinstance(d, dict) and 'status_name' in d]
"""
with open('new_json', 'w', encoding='utf-8') as fp:
json.dump(new_data, fp)
Method 2
import json
with open('.json', encoding='utf-8') as fp:
data = json.load(fp)
new_data = []
for d in data: # use different variable name
# assume d is a dictionary with key 'status_name'
try:
value = d['status_name']
except Exception:
pass # don't append d
else:
new_data.append(d) # no exception so append d
with open('new_json', 'w', encoding='utf-8') as fp:
json.dump(new_data, fp)