将JSON格式数据转化为sql 插入语句

python 复制代码
import json

# 从 txt 文件中读取 JSON 数据
def read_json_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

# 将 SQL 语句写入到 txt 文件中
def write_sql_to_file(output_file_path, sql_statements):
    with open(output_file_path, 'w', encoding='utf-8') as file:
        for sql in sql_statements:
            file.write(sql + '\n')

# 示例文件路径
input_file_path = '文件.txt'  # 输入文件路径
output_file_path = 'InsertSql.sql'  # 输出文件路径

# 读取 JSON 数据
json_data = read_json_from_file(input_file_path)

# 解析 JSON 数据
data = json.loads(json_data)

# 提取 items 列表
items = data["data"]["items"]

# 用于存储已经处理过的 id
processed_ids = set()

# 用于存储生成的 SQL 语句
sql_statements = []

# 生成 SQL 插入语句
for item in items:
    table_name = "data"
    business_data = item[table_name]["businessData"]
    current_id = business_data["id"]
    
    # 检查 id 是否已经处理过
    if current_id in processed_ids:
        # print(f"Skipping duplicate id: {current_id}")
        continue
    
    # 将当前 id 添加到已处理集合中
    processed_ids.add(current_id)
    
    # 构建列名和值
    columns = ', '.join(business_data.keys())
    values = ', '.join([f"'{value}'" if isinstance(value, str) else str(value) for value in business_data.values()])
    
    # 生成 SQL 语句
    sql = f"INSERT INTO {table_name} ({columns}) VALUES ({values});"
    sql_statements.append(sql)

# 将 SQL 语句写入到输出文件中
write_sql_to_file(output_file_path, sql_statements)

print(f"SQL statements have been written to {output_file_path}")

JSON数据格式

{

"status": 1,

"message": "请求成功",

"data": {

"page": 1,

"pageSize": 10,

"total": 30,

"items": [

{

"data": {

"M_SYS_CREATETIME": "2025-02-27 07:20:03",

"M_SYS_MODIFYTIME": "2025-02-27 07:20:03",

"M_SYS_VALIDDATE": "2025-02-27 07:20:03",

"M_SYS_SECRETLEVEL": 1,

"businessData": {

"create_time": "2023-05-06 16:01:08",

"id": 287434114334721,

"is_delete": 0

}

}

},

]

}

}

相关推荐
言乐63 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能10 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
卷无止境11 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131411 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教11 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教12 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境12 小时前
FastAPI 的Admin面板生态
后端·python
麻瓜code12 小时前
【Mysql】重新学一遍 SQL 执行顺序
数据库·sql
ctlover13 小时前
Streamlit 框架
python
ι:13 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机