
本文介绍如何将不含表名的 json 配置(仅含列定义)与外部表名列表结合,生成以表名为键、列映射为值的字典结构,适用于多表共享相同 schema 的场景。
本文介绍如何将不含表名的 json 配置(仅含列定义)与外部表名列表结合,生成以表名为键、列映射为值的字典结构,适用于多表共享相同 schema 的场景。
在实际数据处理或 ETL 场景中,常遇到多个物理表结构完全一致(即列名与语义映射相同),但表名各异的情况。此时,将重复的列定义硬编码到每个表对象中既冗余又难以维护。更优方案是:在 JSON 中只保留一份通用列定义,运行时通过 Python 将其动态绑定到表名列表上。
假设 new_table.json 内容如下(注意:tables 数组中不再包含 "name" 字段,仅保留统一的 columns 结构):
{
"tables": [
{
"columns": {
"column1": "name",
"column2": "address"
}
}
]
}而你的目标表名列表为:
table_list = ['abc', 'rfe', 'try']
由于所有表共用同一份列定义,我们只需提取 mapping_data['tables'][0]['columns'](即第一个表的 columns),再通过字典推导式将其与 table_list 中每个名称配对即可:
立即学习“Python免费学习笔记(深入)”;
import json
table_list = ['abc', 'rfe', 'try']
try:
with open('new_table.json', 'r', encoding='utf-8') as f:
mapping_data = json.load(f)
# 安全提取:确保 tables 非空且存在 columns
tables = mapping_data.get('tables', [])
if not tables:
raise ValueError("JSON 中 'tables' 为空或缺失")
columns = tables[0].get('columns')
if columns is None:
raise ValueError("首个 table 缺少 'columns' 字段")
table_mappings = {table_name: {'columns': columns} for table_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 FileNotFoundError:
print("错误:未找到 new_table.json 文件")
except json.JSONDecodeError as e:
print(f"JSON 解析错误:{e}")
except ValueError as e:
print(f"配置校验错误:{e}")
except Exception as e:
print(f"未知错误:{str(e)}")✅ 关键要点说明:
- 不再遍历 tables 列表(因其仅含一个模板),而是直接取 tables[0];
- 使用 .get() 方法增强健壮性,避免 KeyError;
- 添加基础异常处理,覆盖文件缺失、JSON 格式错误、字段缺失等常见问题;
- 若未来需支持多套不同列定义(如部分表结构不同),可扩展为按索引或标签匹配,但当前单模板模式已足够简洁高效。
该方法显著提升配置可维护性:当列语义变更时,只需修改 JSON 中一处 columns,所有映射自动同步生效。


















