发布于2026-07-04 阅读(0)
扫一扫,手机访问
本文介绍如何利用单个通用 json 表结构模板,结合外部表名列表(如 ['abc', 'rfe', 'try']),高效构建键为表名、值为列定义的字典映射,避免重复 json 冗余,提升配置灵活性与可维护性。
本文介绍如何利用单个通用 json 表结构模板,结合外部表名列表(如 ['abc', 'rfe', 'try']),高效构建键为表名、值为列定义的字典映射,避免重复 json 冗余,提升配置灵活性与可维护性。
在实际的数据处理或 ETL 场景里,经常碰到多张结构完全一致但逻辑名称不同的表——比如按业务域或时间分片的那种。这时候,要是把每张表的列映射都硬编码进 JSON,那冗余量就太大了。一个更聪明的做法是:把“结构模板”和“实例命名”拆开。说白了,就是先用一份精简的 new_table.json 定义好共用的列结构,再通过 Python 批量把它绑定到动态表名列表上,干净利落。
下面直接上完整方案。
new_table.json 里的 tables 数组只放了一个通用模板(tables[0]),所以我们不用遍历整个 tables,直接把那个模板的 columns 提取出来,然后跟 table_list 里的每个名字一一配对就行:
import json
table_list = ['abc', 'rfe', 'try']
try:
with open('new_table.json', 'r', encoding='utf-8') as f:
mapping_data = json.load(f)
# 核心:取首个(且唯一)模板的 columns,为每个表名创建映射项
template_columns = mapping_data['tables'][0]['columns']
table_mappings = {name: {'columns': template_columns} for name in table_list}
print(table_mappings)
# 输出示例:
# {
# 'abc': {'columns': {'column1': 'name', 'column2': 'address'}},
# 'rfe': {'columns': {'column1': 'name', 'column2': 'address'}},
# 'try': {'columns': {'column1': 'name', 'column2': 'address'}}
# }
except KeyError as e:
print(f"JSON 结构错误:缺失预期字段 {e}")
except FileNotFoundError:
print("错误:未找到 new_table.json 文件")
except json.JSONDecodeError as e:
print(f"JSON 解析失败:{e}")
except Exception as e:
print(f"未知错误:{e}")tables = mapping_data.get('tables', [])
if not tables:
raise ValueError("JSON 中 'tables' 数组为空,无法获取列模板")
template_columns = tables[0].get('columns')
if not isinstance(template_columns, dict):
raise ValueError("'columns' 字段必须为字典类型")这个方法兼顾了简洁和可维护性,算是配置驱动开发(Configuration-as-Code)里很典型的实践了。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8