Friday 10 September 2021

Pydantic: Customize serialization

You can customize the Serialisation on a model using the json_encoders config property, the keys should be types, and the values should be functions which serialise that type.

 

json_customize_serialization.py

from pydantic import BaseModel, ValidationError
from datetime import datetime

class Employee(BaseModel):
    id: int
    name: str
    age: int
    dateOfBirth: datetime

    class Config:
        json_encoders = {
            datetime: lambda v: v.timestamp()
        }

emp1 = Employee(id = 1, name = 'Ptr', age = 23, dateOfBirth = datetime(1988, 6, 6, 12, 13, 14))
emp1Json = emp1.json()

print('emp1Json -> ' + emp1Json)

 

Output

emp1Json -> {"id": 1, "name": "Ptr", "age": 23, "dateOfBirth": 581582594.0}

Note

In case of inheritance, child encoders take precedence over parent encoders.


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment