Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to serialize list of list items to pydantic model

I have response from server:

{
    "date": "2024-02-05 15:34:44",
    "status": True,
    "data": [
        [1, "red"],
        [2, "blue"],
        [3, "yellow"]
    ]
}

And i want to serialize this response to pydantic model, but i don’t know how parse list (example [1, "red"]) in pydantic model

class Item(BaseModel): # how convert list from data to this model
    id: int
    color: str
    ...


class Model(BaseModel):
    date: datetime
    status: bool
    data: list[Item]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can work for example with a model_validator to parse the list into the Item model:

from pydantic import BaseModel, model_validator

data = {
    "date": "2024-02-05 15:34:44",
    "status": True,
    "data": [
        [1, "red"],
        [2, "blue"],
        [3, "yellow"]
    ]
}

class Item(BaseModel):
    id: int
    color: str

    @model_validator(mode="before")
    @classmethod
    def validate(cls, values):
        id, color = values
        return {"id": id, "color": color}
    


class Model(BaseModel):
    date: datetime
    status: bool
    data: list[Item]


print(Model(**data))

Which prints:

date=datetime.datetime(2024, 2, 5, 15, 34, 44) status=True data=[Item(id=1, color='red'), Item(id=2, color='blue'), Item(id=3, color='yellow')]

There are likely other approaches, such as AliasPath, but this one seems the simplest.

I hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading