I have a JSON file that has a number of objects that have parent, child relationships. This is what the JSON looks like at a high-level.
{
"objectType1": {
"objectType1ID1": {
"parent": {},
"children": [{"id":"objectType2ID2"}],
"properties": {}
},
"objectType1ID2": {
"parent": {},
"children": [{}],
"properties": {}
}
},
"objectType2": {
"objectType2ID1": {
"parent": {},
"children": [],
"properties": {}
},
"objectType2ID2": {
"parent": {"id":"objectType1ID1"},
"children": [],
"properties": {}
}
}
}
The first level keys contain the various types of objects and then within each type there are any number of objects of that type that contain parent, children (list), and properties keys. Each object can have at most one parent object or many children objects in a list.
I am trying to build a Pydantic model for this structure. Below is what I have so far but I am new to Pydantic and I am stuck.
from pydantic import BaseModel
from typing import List, Optional
class ObjectParent(BaseModel):
id: Optional[str]
class ObjectChild(BaseModel):
id: Optional[str]
class Properties(BaseModel):
name: Optional[str]
description: Optional[str]
class Object(BaseModel):
id: str
parent: Optional['ObjectParent'] = None
children: List['ObjectChild'] = []
properties: Properties
root_validatorto the structure you need. you can think of pydantic is a complex storage validation tool.Objectas a classname, it may cause overriding of default behavior, perhaps useJsonObjector something more specific instead?objectType1) is a challenge. Definitely doable, but tricky.