You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将列表表名与无表名JSON的列结构映射

正确实现方案

完整可运行代码

import json

table_list = ['abc', 'rfe', 'try']

try:
    with open('new_table.json', 'r', encoding='utf-8') as f:
        mapping_data = json.load(f)
        # 提取JSON中唯一的列结构
        column_config = mapping_data.get('tables', [{}])[0].get('columns', {})
        # 生成表名与列结构的映射字典
        table_mappings = {table_name: {'columns': column_config} for table_name in table_list}
        print(table_mappings)
except Exception as e:
    print(f"error: {str(e)}\n")

原代码的问题分析

  1. 字典推导式语法错误:Python字典推导式的正确格式是{键表达式: 值表达式 for 变量 in 可迭代对象},你写的{for i in table_list: ...}不符合语法规范。
  2. 逻辑冗余:当前场景下JSON里只有一套列结构,只需要提取一次,再逐个绑定到表名上即可,不需要同时遍历表名列表和JSON中的tables数组。

输出结果示例

运行后会生成如下结构的字典:

{
    'abc': {'columns': {'column1': 'name', 'column2': 'address'}},
    'rfe': {'columns': {'column1': 'name', 'column2': 'address'}},
    'try': {'columns': {'column1': 'name', 'column2': 'address'}}
}

内容的提问来源于stack exchange,提问作者Lara19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:32:48