将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

}

}

},

]

}

}

相关推荐
hhzz31 分钟前
Pythoner 的Flask项目实践-绘制点/线/面并分类型保存为shpfile功能(Mapboxgl底图)
python·flask·gis·mapboxgl
学IT的周星星1 小时前
《MyBatis变形记:当SQL遇上“智能管家“》
数据库·sql·mybatis
Lxinccode1 小时前
python(42) : 监听本地文件夹上传到服务器指定目录
服务器·开发语言·python·文件上传服务器·监听文件上传服务器
我是华为OD~HR~栗栗呀2 小时前
前端面经-高级开发(华为od)
java·前端·后端·python·华为od·华为·面试
木头左2 小时前
跨周期共振效应在ETF网格参数适配中的应用技巧
开发语言·python·算法
爱蹦跶的精灵2 小时前
降级版本Pillow解决freetypefont has no attribute getsize问题
python·pillow
野老杂谈2 小时前
Hive SQL 中的时间戳转换详解
hive·hadoop·sql
嘉禾望岗5032 小时前
hive SQL查询与函数
hive·hadoop·sql
一人の梅雨2 小时前
亚马逊 MWS 关键字 API 实战:关键字搜索商品列表接口深度解析与优化方案
python·spring
程序新视界3 小时前
MySQL的两种分页方式:Offset/Limit分页和游标分页
后端·sql·mysql