R Mahmood R Mahmood - 3 months ago 16
JSON Question

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?

Answer

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']}}
Comments