我有一个嵌套循环,可以按照我想要的方式获取某些JSON元素,但是偶尔,我从中获取的API会变得混乱,并且会破坏某些字段-我不确定如何处理此问题,因为似乎每次都不同,所以我想知道是否有一种方法可以继续嵌套的for循环,即使其中发生异常,还是至少返回第一个循环并再次继续。
我的代码是这样的:
fields = ['email', 'displayname', 'login']
sub_fields = ['level', 'name']
all_data = []
for d in data:
login_value = d['login']
if login_value.startswith('3b3'):
continue
student = fetched_student.student_data(login_value)
student = json.loads(student)
final_json = dict()
try:
for field in fields:
#print ("Student field here: %s" % student[field])
final_json[field] = student[field]
except Exception as e:
print (e) # this is where I get a random KeyValue Error
#print ("Something happening here: %s " % final_json[field])
finally:
for sub_field in sub_fields:
for element in student['users']:
if element.get(sub_field):
final_json[sub_field] = element.get(sub_field)
for element in student['campus']:
if element.get(sub_field):
final_json[sub_field] = element.get(sub_field)
all_data.append(final_json)
print (all_data)
是否有办法仅返回第一个try块并在异常发生后继续运行,或者只是忽略它并继续运行? 因为就像现在一样,如果异常发生,它将破坏一切。
EDIT1:我尝试过像这样继续:
try:
for field in fields:
#print ("Student field here: %s" % student[field])
final_json[field] = student[field]
except Exception as e:
print (e)
continue
for sub_field in sub_fields:
for element in student['users']:
但是无论如何它仍然会失败。
答案 0 :(得分:1)
将其用于try块:
for field in fields:
try:
#print ("Student field here: %s" % student[field])
final_json[field] = student[field]
except Exception as e:
print (e)
continue
for sub_field in sub_fields:
for element in student['users']:
问题是由于try块的缩进级别,继续影响了最外面的循环。将try块更改为循环内部将捕获该循环中的错误,并继续该特定循环的迭代。
答案 1 :(得分:0)
可能您可以在dict
块中使用try
的get方法:
try:
for field in fields:
#print ("Student field here: %s" % student[field])
final_json[field] = student.get(field, "") # 2nd arg is fallback object
根据需要,您可以传入新鲜的dict
(又名JSON对象),新鲜的list
(又名JSON数组)或上面的str
来适合您的需求下游需求。