根据用户输入更新 JSON

我想根据用户的输入使用 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 json



s_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 作为数据库是一个好习惯吗?


萧十郎
浏览 118回答 2
2回答

芜湖不芜

每次保存数据时都会截断文件。使用“ 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)

慕尼黑5688855

关于你的问题,使用 sqlite3 (加上 python)来更新数据库更容易。一探究竟!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python