亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據用戶輸入更新 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 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號