简体   繁体   中英

Pythonic way to update multiple values stored within a json dict

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"
    }
}

code:

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")

result:

{
    "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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM