Python处理嵌套JSON:避免KeyError的简洁实现方法求助
简洁实现方案
可以通过以下几种方式避免重复编写if判断,简化代码:
1. 直接利用get()默认值+短路求值
通过raw_output.get('raw_col1', [])给父字段设置默认空列表,再结合列表生成式的结果做短路判断,空列表会被转换为None,和原逻辑完全一致:
self.test_col_1 = [o.get('raw_value1') for o in raw_output.get('raw_col1', [])] or None
- 原理:
get('raw_col1', [])确保父字段不存在时返回空列表,避免KeyError;空列表在布尔判断中为False,通过or None将空列表转为None,和原if-else的结果一致;o.get('raw_value1')本身默认返回None,无需额外写or None。
2. 封装通用提取函数
如果涉及大量字段,可将提取逻辑封装成函数,复用代码:
def extract_nested_field(data, parent_key, child_key): # 获取父字段,默认空列表 parent_items = data.get(parent_key, []) # 生成子字段列表,空列表则转为None return [item.get(child_key) for item in parent_items] or None # 调用赋值 self.test_col_1 = extract_nested_field(raw_output, 'raw_col1', 'raw_value1') self.test_col_2 = extract_nested_field(raw_output, 'raw_col2', 'raw_value2') # 其他字段依此类推
3. 批量处理字段映射
若字段数量极多,可定义字段映射关系,通过循环批量赋值,进一步减少重复代码:
def extract_nested_field(data, parent_key, child_key): parent_items = data.get(parent_key, []) return [item.get(child_key) for item in parent_items] or None # 定义实例属性与JSON字段的映射:(实例属性名, JSON父字段, JSON子字段) field_mappings = [ ('test_col_1', 'raw_col1', 'raw_value1'), ('test_col_2', 'raw_col2', 'raw_value2'), ('test_col_3', 'raw_col3', 'raw_value3'), # 新增字段只需在此添加映射 ] # 循环批量赋值 for attr_name, parent_key, child_key in field_mappings: setattr(self, attr_name, extract_nested_field(raw_output, parent_key, child_key))
内容的提问来源于stack exchange,提问作者VN-
相关产品推荐
相关产品推荐

