import json import pymysql JSON_FILE = "base_templates.json" DB_CONFIG = { "host": "127.0.0.1", "user": "root", "password": "root", "database": "recycle", "charset": "utf8mb4", "cursorclass": pymysql.cursors.DictCursor } def remove_value_text(obj): """ 递归删除所有 valueText 字段 """ if isinstance(obj, dict): obj.pop("valueText", None) for k, v in obj.items(): remove_value_text(v) elif isinstance(obj, list): for item in obj: remove_value_text(item) def main(): with open(JSON_FILE, "r", encoding="utf-8") as f: data = json.load(f) conn = pymysql.connect(**DB_CONFIG) try: with conn.cursor() as cursor: for template_id, template_data in data.items(): # 深拷贝一份,避免污染原对象 cleaned = json.loads(json.dumps(template_data)) # 删除 valueText remove_value_text(cleaned) template_version = str(cleaned.get("templateVersion")) template_json = json.dumps( cleaned["template"], ensure_ascii=False ) sql = """ INSERT INTO base_estimate_template (template_id, template_version, template_json) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE template_version = VALUES(template_version), template_json = VALUES(template_json) """ cursor.execute( sql, ( int(template_id), template_version, template_json ) ) print(f"导入模板 {template_id} 成功") conn.commit() finally: conn.close() if __name__ == "__main__": main()