为了账号安全,请及时绑定邮箱和手机立即绑定

根据用户输入更新 JSON

根据用户输入更新 JSON

萧十郎 2023-07-05 16:30:38
我想根据用户的输入使用 JSON 创建数据库。我已经编写了这段代码,但它用新数据替换了整个文件,并且不更新现有的 JSON 文件。文件database.json给出的输出为{"Employee ID": "ID2", "Employee Name": "Friendrich", "Domain": "Engineering", "Employee Type": "Permanent", "Start Date": "01.02.2020", "End Date": "28.02.2021"}import jsons_id = input('employeeID')s_name = input('employeeName')s_domain = input('domain')s_type = input('employeeType')s_from = input('start-date')s_until = input('end-date')database = {        'Employee ID' : s_id,        'Employee Name' : s_name,        'Domain' : s_domain,        'Employee Type' : s_type,        'Start Date' : s_from,        'End Date' : s_until        }with open('database.json') as json_file:    data = json.load(json_file)data.update(database)with open('database.json', 'w') as json_file:    json.dump(database, json_file)使用新输入时,json 文件应将数据添加到现有文件中。所以输出应该是{"Employee ID": "new ID", "Employee Name": "input name", "Domain": "input domain", "Employee Type": "input type", "Start Date": "input date", "End Date": "input date"}, {"Employee ID": "ID2", "Employee Name": "Friendrich", "Domain": "Engineering", "Employee Type": "Permanent", "Start Date": "01.02.2020", "End Date": "28.02.2021"}, 我创建这个数据库是为了找到具有特定过滤器的所有员工。假设所有具有工程领域的员工。使用 JSON 作为数据库是一个好习惯吗?
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

每次保存数据时都会截断文件。
使用“ a ”而不是“ w ”作为打开模式。

代替

with open('database.json', 'w') as json_file:
    json.dump(database, json_file)

with open('database.json', 'a') as json_file:
    json.dump(database, json_file)


查看完整回答
反对 回复 2023-07-05
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

关于你的问题,使用 sqlite3 (加上 python)来更新数据库更容易。一探究竟!



查看完整回答
反对 回复 2023-07-05
  • 2 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信