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
}
}
},
]
}
}