简体   繁体   中英

Python append json object in file, guard if object does not exist

I am reading in a json file using python, and then appending in an array within an object, the shape of this being

"additional_info": {"other_names": ["12.13"]

I am appending the array as follows:

data["additional_info"]["other_names"].append('13.9')
with open('jsonfile', 'w') as f:
    json.dump(data, f)

I want to set a guard to check if additional_info and other_names exists in the json file and if it doesn't then to create it. How would I go about doing this?

Usually I would use nested try-except to check for each missing key or a defaultdict , but in this case I think I would go with 2 if statements for the sake of simplicity:

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

with open('jsonfile', 'w') as f:
    json.dump(data, f)

Two use cases:

data = {}

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

print(data)
>> {'additional_info': {'other_names': ['13.9']}}

And

data = {"additional_info": {"other_names": ["12.13"]}}

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

print(data)
>> {'additional_info': {'other_names': ['12.13', '13.9']}}

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