如果在python中发生错误,则处理异常

时间:2017-10-25 09:26:36

标签: python json for-loop error-handling exception-handling

当我尝试解析JSON字符串时,我收到少量记录的错误,我无法处理异常,如果在解析JSON字符串时发生错误,则跳过该记录并移至下一条记录。

以下是代码段。

ID=[]
json_string=[]
for row in cursor.fetchall():
 ID.append(row[0]) 
 json_string.append(row[1])
address_fields = {
'intersection': [],        
'political': [],        
'country': [], 
}
dumpData = json.dumps(json_string)
json_all = json.loads(dumpData)

id_index = 0
for json_str in json_all:
     address_fields = {
      'intersection': [],        
      'political': [],        
      'country': [], 
      }
     try:
      json_results = json.loads(json_str)
     except IndexError:
      continue


     if isinstance(json_results,dict):
         first_address_components = json_results['results'][0]['address_components']
     else:
         first_address_components = json_results[0]['address_components']
     for item in first_address_components:
         for field_key in address_fields.keys():
            if field_key in item['types']:
               address_fields[field_key].append(item['long_name'])

我首先从sql表中获取数据并存储take JSON_string及其ID并尝试解析JSON字符串并更新sql表中的那些,因此对于那些我收到错误的JSON字符串,我想跳过该行并移动到下一个记录。 但这还没有完成。不过,我无法处理异常。 任何帮助都会有所帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

而不是这个

try:
  json_results = json.loads(json_str)
except IndexError:
  continue

这样做。

try:
    json_results = json.loads(json_str)
except:
     pass
相关问题