I have a script that requires certain keys from a JSON file. If any keys are missing or if the JSON file is corrupted (missing an end }
or whatever) it will break. While trying to make a script that will open the JSON file and attempt to fix these error, I learned that .setdefault()
does not set nested keys. I do not want to make nested for loops or make some crazy function that checks every key manually and so, after testing anything I could find on SO and still failing, I have come here. I have made a minimum reproducible example showing what should happen and what does happen. How can I get a function that will set all the required keys to be added for large dictionaries that are nested multiple times?
# NOTE: to run this, make a test.json file
import json
#test.json: {"dict":{"Key3": "Value1"}
# What should be the output of this script: {"dict":{"Key3": "Value1", "Key1": "Value1", "Key2": "Value2"}}
default_dict = {
"dict":{
"Key1": "Value1",
"Key2": "Value2"
}
}
# I want to make sure that all the keys in default_dict are present in test.json
# Any extra keys in test.json should be left alone
with open("test.json", "r+") as f:
# First check if the file is a broken json file
try:
content: dict = json.load(f)
except json.decoder.JSONDecodeError:
# If it is, delete the file content and replace it with the default_dict
# I would prefer a way to just fix the issue but I have no idea how that would be accomplished
f.seek(0)
f.truncate()
f.write(json.dumps(default_dict, indent=4))
content: dict = default_dict
#Check that all keys are present
for key in default_dict:
content.setdefault(key, default_dict[key])
# json dump
#Delete the file content
f.seek(0)
f.truncate()
json.dump(content, f, indent=4)
#Load the json file
with open("test.json", "r") as f:
content: dict = json.load(f)
print(content)
#Output (The exact same as before!):
"""
{'dict': {'Key3': 'Value1'}}
"""