问题描述
为了避免在代码中使用Keyerror
,我应该做的是菜鸟,:)
我加载json并通过标签status_name
打印数组中的所有值,但是算法在Keyerror
上失败了,我该如何处理它然后将结果列表保存到文件中? >
import json
with open(r'.json',encoding='utf-8') as fp:
data = json.load(fp)
for data in data:
print(data['status_name'])
我根据请求从所有标签status_name
获取数据,但是当请求到达没有标签status_name
的标签时,我得到:
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
我不打印任何内容或跳过此类块
解决方法
您的数据似乎没有名为“ status_name”的键。尝试先仅打印数据,然后查看所需的实际密钥。
关于将其保存在文件中,您可以使用“ w”模式打开文件,然后在循环末尾写入数据。像这样:
file = open(data.txt,'w')
对于数据中的d:
print(d ['status_name'])
file.write(d)
我将“数据”更改为“ d”,因为这有点令人困惑。
别忘了在循环后关闭文件。
,有两种处理错误的方法:
方法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)
方法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',fp)
,
import xlwt
import json
with open(r'name.json',encoding='utf-8') as fp:
data = json.load(fp)
channels = set() # unique data
for item in data['items']:
if 'status_name' in item: #checking if there is a tag,bypass Keyerror
channels.add(item['status_name'])
print(item['status_name'])
print(channels) # print unique data
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet Name")
# Writing on specified sheet
sheet.write(0,'Channels')
row = 1
for channel in sorted(channels):
sheet.write(row,channel)
row += 1
workbook.save("name.xls")