with open('Data.json', 'r+') as fp:
json_file = json.load(fp)
keys = json_file.keys()
if today_date in keys:
json_file[today_date].update({"guonei":covid_newadd_shanghai_number,"changning":covid_newadd_changning_number})
else:
json_file.update({today_date:{"guonei":covid_newadd_shanghai_number,"changning":covid_newadd_changning_number}})
#json_file.update(json_file)
fp.seek(0,0) #个人理解是为了刷新json文件
fp.truncate() #网上解释,这句不加的话,后加入的内容有可能变成非json格式(乱加括号,大括号)。
fp.write(json.dumps(json_file))
Data.json:
{"0426": {"guonei": "1,908", "changning": "97"}, "0427": {"guonei": "1,820", "changning": "64"}, "0425": {"guonei": "2,697", "changning": "76"}, "0423": {"guonei": "00", "changning": "00"}}