如何在 Python 中将 JSON 模板与动态表名列表映射生成结构化映射字典

如何在 Python 中将 JSON 模板与动态表名列表映射生成结构化映射字典

本文介绍如何利用单个通用 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}")

⚠️ 注意事项

  • 健壮性增强:原答案中 mapping_data[‘tables’][0] 假设数组非空且至少有一个元素。生产环境建议添加校验:

    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' 字段必须为字典类型")
  • 扩展性提示:若未来需支持不同表使用不同模板(如 table_list 与 templates 列表长度一致),可改用 zip(table_list, templates) 实现一一对应。
  • 编码安全:始终显式指定 encoding=’utf-8’,避免跨平台读取乱码。

该方法兼顾简洁性与可维护性,是配置驱动开发(Configuration-as-Code)的典型实践。

立即学习“Python免费学习笔记(深入)”;

文章来自机圈观察员网,发布者:,转载请注明出处:https://www.jqgcy.com/xitongjiaocheng/124161.html

怎样在ThinkPHP中实现数据库连接信息加密【安全】
上一篇 2026-07-01 18:13
下一篇 2026-07-01 18:13

相关推荐