Python中如何避免覆盖JSON内容并正确追加新条目
解决Python中JSON存储嵌套字典的追加问题
我用Python写代码时,想用JSON存储嵌套字典数据,但每次追加都会生成新的独立字典,而不是在原字典里添加新键值对,导致JSON文件格式错误无法正常读取。
目标JSON格式
{ "1234": { "Name": "wkwkw", "Age": "15" }, "54321": { "Name": "wkwkw", "Age": "15" } }
当前错误的JSON输出
{ "1234": { "Name": "wkwkw", "Age": "15" } } { "54321": { "Name": "wkwkw", "Age": "15" } }
原代码
def register(self): self.emp_id = input("Employee ID: ") self.password = input("Password: ") employee_record = {} employee_details = {self.emp_id : employee_record} employee_record["Employee ID"] = self.emp_id employee_record["Password"] = self.password employee_record["Job"] = self.job employee_record["Name"] = self.name employee_record["Age"] = self.age employee_record["Gender"] = self.gender employee_record["Contact Number"] = self.contact_no print("Registration Successful!") #print(employee_record) with open('emp_details.json', 'w') as fp: json.dump(employee_details, fp, indent=4) fp.close() def login(self): file = open("emp_details.json", 'r') emp_login_details = json.load(file) print (emp_login_details) self.emp_id = input("Enter login ID: ") self.password = input("Enter your password: ") if self.emp_id in emp_login_details[self.emp_id]["Employee ID"]: if self.password in emp_login_details[self.emp_id]["Password"]: print("You are now logged in!") else: print("You are not logged in!") file.close()
解决方案
1. 修复注册逻辑:读取已有数据再追加
当前代码用'w'模式打开文件会直接覆盖原有内容,且未读取已存字典。正确做法是先加载现有数据(文件不存在或为空则初始化空字典),再将新员工数据添加进去,最后写入文件。
修改后的register方法:
import json # 确保导入json模块 def register(self): self.emp_id = input("Employee ID: ") self.password = input("Password: ") # 直接构建员工详情字典,简化代码 employee_record = { "Employee ID": self.emp_id, "Password": self.password, "Job": self.job, "Name": self.name, "Age": self.age, "Gender": self.gender, "Contact Number": self.contact_no } print("Registration Successful!") # 读取已有数据,处理文件不存在或空文件的情况 try: with open('emp_details.json', 'r') as fp: employee_details = json.load(fp) except (FileNotFoundError, json.JSONDecodeError): employee_details = {} # 添加新员工到字典 employee_details[self.emp_id] = employee_record # 写入文件,覆盖原有内容(此时是包含新数据的完整字典) with open('emp_details.json', 'w') as fp: json.dump(employee_details, fp, indent=4)
2. 修复登录逻辑的判断错误
原登录代码的判断逻辑有误,应该先检查员工ID是否存在于字典的键中,再对比密码。
修改后的login方法:
def login(self): # 处理文件不存在或读取失败的情况 try: with open("emp_details.json", 'r') as file: emp_login_details = json.load(file) except (FileNotFoundError, json.JSONDecodeError): print("No employee records found!") return self.emp_id = input("Enter login ID: ") self.password = input("Enter your password: ") # 正确的验证逻辑 if self.emp_id in emp_login_details: if emp_login_details[self.emp_id]["Password"] == self.password: print("You are now logged in!") else: print("Incorrect password!") else: print("Employee ID not found!")
3. 注意JSON格式规范
JSON要求所有键必须用双引号包裹,虽然json.dump会自动处理字典的键,但手动编写示例时要注意格式,避免出现语法错误。
内容的提问来源于stack exchange,提问作者dwextit
相关产品推荐
相关产品推荐

