I have a json file in which I store a dictionary of values. I know how to modify the value of a key individually, but I want to know how to update the dictionary within the json file with another dictionary.
json file called 'dummy.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"
}
}
Code
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
New dictionary I want to use to update dummy.json
new_data = {"volts": 20.0,
"power": 11.1,
"current": 2.2}
Desired output
{
"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"
}
}
.update(new_dict)this will work..