I've a dictionary that is to be parsed to a JSON format. The dictionary looks like this:
{'transportation': {'airplane': {'properties': {'fly': {'type': 'string'}, 'pilot': {'type': 'string'}}}, 'car': {'properties': {'drive': {'type': 'string'}, 'driver': {'type': 'string'}}}, 'boat': {'properties': {'sail': {'type': 'string'}, 'sailer': {'type': 'string'}}}}}
I want to add a required object to the dictionary with an array of elements. Therefore I've a recursive function to look through objects and insert the values at the correct level.
My code looks like this:
dataReqProp = (
['airplane', 'fly'],
['boat', 'sail'],
['car', 'driver'],
['boat', 'sailer']
)
obj = {'transportation': {'airplane': {'properties': {'fly': {'type': 'string'}, 'pilot': {'type': 'string'}}}, 'car': {'properties': {'drive': {'type': 'string'}, 'driver': {'type': 'string'}}}, 'boat': {'properties': {'sail': {'type': 'string'}, 'sailer': {'type': 'string'}}}}}
def update_required_json(obj, target_key, update_value):
if isinstance(obj, dict):
for key, value in obj.items():
if key == target_key:
# obj[key].setdefault(json_type, {}).update(update_value)
obj[key].update({'required': update_value})
update_required_json(value, target_key, update_value)
elif isinstance(obj, list):
for entity in obj:
update_required_json(entity, target_key, update_value)
for key, prop in dataReqProp:
new_prop = [prop]
update_required_json(obj, key, new_prop)
print(obj)
However it does only add one element to the required object. Boat should have the sailer and sail. What am I overlooking here?
I get the following output:
{'transportation': {'airplane': {'properties': {'fly': {'type': 'string'}, 'pilot': {'type': 'string'}}, 'required': [['fly']]}, 'car': {'properties': {'drive': {'type': 'string'}, 'driver': {'type': 'string'}}, 'required': [['driver']]}, 'boat': {'properties': {'sail': {'type': 'string'}, 'sailer': {'type': 'string'}}, 'required': ['sailer']}}}
But I expect that below boat the required array is only filled with one element. I expect that "sail" should be there as well.
CodePudding user response:
Your issue is with this line:
obj[key].update({'required': update_value})
which is overwriting the required
key when you try to add a second value, not updating it. You can use setdefault
to work around that:
def update_required_json(obj, target_key, update_value):
if isinstance(obj, dict):
for key, value in obj.items():
if key == target_key:
obj[key].setdefault('required', []).extend(update_value)
update_required_json(value, target_key, update_value)
elif isinstance(obj, list):
for entity in obj:
update_required_json(entity, target_key, update_value)