当用户“帐号”已存在时,我正试图阻止json.dump
写入我的JSON文件。
这是我的代码:
new_student = {"name": 'test2', "account_no": 1237}
account_no = 1346
with open("student.json", "r", encoding="utf-8") as f:
data = json.load(f)
for a in data["student_numbers"]:
if not account_no == a["account_no"]:
data["student_numbers"].append(new_student)
with open("student.json", "w", encoding="utf-8") as f:
json.dump(data, f)
break
这也是我的JSON:
{"student_numbers": [{"account_no": 1345, "name": "test"}, {"account_no": 1346, "name": "test2"}, {"account_no": 1347, "name": "test3"}]}
我试过了if account_no not in a["account_no"]
,但我收到了这个错误:
TypeError`TypeError:'int'类型的参数不可迭代
答案 0 :(得分:0)
new_student = {"name": 'test2', "account_no": 1237}
with open("student.json", "r", encoding="utf-8") as f:
data = json.load(f)
existed_ids = {a['account_no'] for a in data["student_numbers"]} # set of ids
if new_student['account_no'] not in existed_ids:
with open("student.json", "w", encoding="utf-8") as f:
data['student_numbers'].append(new_student)
json.dump(data, f)
答案 1 :(得分:0)
您的检查失败,因为当您遍历student_numbers
时,这些是返回的account_no
,即:1345,1346和1347.所以您在第一次迭代中看到,您的条件是已经满足因为1346!= 1345,所以json.dump()
被激活了。
您想要的是创建account_no
列表并使用in
运算符进行检查。您不需要遍历students_numbers
。
new_student = {"name": 'test2', "account_no": 1237}
account_no = 1346
with open("student.json", "r", encoding="utf-8") as f:
data = json.load(f)
accounts = [a["account_no"] for a in data["student_numbers"]]
if account_no not in accounts:
data["student_numbers"].append(new_student)
with open("student.json", "w", encoding="utf-8") as f:
json.dump(data, f)