根据用户输入更新JSON

时间:2020-08-31 12:40:48

标签: python 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用作数据库是一种好习惯吗?

2 个答案:

答案 0 :(得分:2)

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

请参见https://docs.python.org/3.8/library/functions.html#open

替换

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)

答案 1 :(得分:0)

关于您的问题,使用sqlite3(加上python)更新数据库更加容易。看看吧!