So I'm working on a dictionary to build a json schema. Using a recursive function which works pretty well when appending properties to these objects. However, I want to add an array to the object properties. So for this I've attached the following code as an example:
import json
dataProp = (
['airplane', 'fly'],
['car', 'drive'],
['boat', 'sail'],
['airplane', 'pilot'],
['car', 'driver'],
['boat', 'sailer']
)
dataReqProp = (
['airplane', 'fly'],
['boat', 'sail'],
['car', 'driver'],
['boat', 'sailer']
)
obj = {'transportation': {'airplane': {}, 'car': {}, 'boat': {}}}
def update_panel_json(obj, target_key, update_value, json_type):
if isinstance(obj, dict):
for key, value in obj.items():
if key == target_key:
obj[key].setdefault(json_type, {}).update(update_value)
update_panel_json(value, target_key, update_value, json_type)
elif isinstance(obj, list):
for entity in obj:
update_panel_json(entity, target_key, update_value, json_type)
for key, prop in dataProp:
new_prop = {prop: {"type": "string"}}
json_type = 'properties'
update_panel_json(obj, key, new_prop, json_type)
for key, prop in dataReqProp:
new_prop = {prop}
json_type = 'required'
update_panel_json(obj, key, new_prop, json_type)
# obj['transportation']['airplane']['required'] = ['test', 'test2','test3']
#Format dictionary to JSON format
jsonSchema = json.dumps(obj)
pretty_json = json.loads(jsonSchema)
print (json.dumps(pretty_json, indent=2))
In the code there are two arrays. The first array results in a list of objects in the dictionary. The second array contains the same objects but with only required properties. When doing this in the example I get the following error:
ValueError: dictionary update sequence element #0 has length 3; 2 is required
I know that this has something to do with giving more than one value to the update function of the array. However I want to get something like this:
in the required object for each separate object:
airplane object
"required": ["fly"]
boat object
"required": ["sail"]
and so on
In case there are more properties required for one object it should be added to this same array. For instance
boat object
"required": ["sail","row"]
How do I resolve this error issue?