Dynamically Creating nested models in Pydantic

730 Views Asked by At

I'm trying to parse AWS GuardDuty Json data, however some nested datafields are finding specific. Is there are way of doing something like this in pydantic:

from pydantic import Basemodel
from pydantic.main import create_model

class AwsModel(BaseModel):
  accountID: str
  service: create_model("ServiceModel")
  

and have pydantic create the service field as a dynamic model?

Clarification

I've tried this on some test data:

from pydantic import BaseModel
from pydantic.main import create_model

data = {
        "test": "test",
        "dynamic_json":{
            "dyn1": "dyn1_v",
            "dyn2": "dyn2_v",
            "dyn3": "dyn3_v"
            },
        "test2":"test2"
        }

class TestModel(BaseModel):
    test: str
    dynamic_json: create_model("dynamic_json")
    test2: str

m = TestModel.parse_obj(data)
print(m)

output: test='test' dynamic_json=dynamic_json() test2='test2'

it's created an object called dynamic_json with no fields within it, how would I get pydantic to take the nested json data and build the model from the data?

0

There are 0 best solutions below