更新json dict中存储的多个值的Python方法



我有一个json文件,其中存储了一个值字典。我知道如何单独修改键的值,但我想知道如何用另一个字典更新json文件中的字典。

名为"dummy.json"的json文件

{
"my_settings": {
"volts": "21.8",
"power": "25.8",
"current": "1.0",
"time_on": 88888.0,
"time_off": "1.5",
"week": 444,
"site": 4,
"op": "ABC",
"test": "Ubik",
"repeats": 7,
"freq": "6000",
"SN": "3",
"Vpeak": 27.5,
"Vrms": 26.8,
"Foobar": "True"
}
}

代码

json_file = 'dummy.json'
def modify_json_file(json_file, settings_dict, settings_dict_key, new_dict_value):
with open(json_file, "r") as input_json:
json_data = json.load(input_json)
dict_to_modify = json_data[settings_dict]
dict_to_modify[settings_dict_key] = new_dict_value
with open(json_file, "w") as input_json:
json_data[settings_dict]=dict_to_modify
json_data = json.dump(json_data, input_json, indent = 4)
modify_json_file(json_file, "my_settings", "week", 444) # works

我想用来更新dummy.json的新字典

new_data = {"volts": 20.0,
"power": 11.1,
"current": 2.2}

所需输出

{
"my_settings": {
"volts": 20.0,
"power": 11.1,
"current": 2.2,
"time_on": 88888.0,
"time_off": "1.5",
"week": 444,
"site": 4,
"op": "ABC",
"test": "Ubik",
"repeats": 7,
"freq": "6000",
"SN": "3",
"Vpeak": 27.5,
"Vrms": 26.8,
"Foobar": "True"
}
}

代码:

import json
json_file = 'dummy.json'
def update_json_file(json_file,new_dict,key_name):
with open(json_file, "r+") as input_json:
json_data = json.load(input_json)
json_data[key_name].update(new_dict[key_name])
input_json.seek(0)
json.dump(json_data, input_json, indent = 4)
input_json.truncate()
new_dict = {"my_settings":{"volts": 20.0,"power": 11.1,"current": 2.2}}
update_json_file(json_file,new_dict,"my_settings")

结果:

{
"my_settings": {
"volts": 20.0,
"power": 11.1,
"current": 2.2,
"time_on": 88888.0,
"time_off": "1.5",
"week": 444,
"site": 4,
"op": "ABC",
"test": "Ubik",
"repeats": 7,
"freq": "6000",
"SN": "3",
"Vpeak": 27.5,
"Vrms": 26.8,
"Foobar": "True"
}
}

相关内容

最新更新