Search code examples
pythonpydantic

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]

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!