How can I define a mapping between a json property to a pydantic model where the property name is different?. ie:
# I want to parse thumbnailUrl into thumbnail
class ChatMessageAttachment(BaseModel):
id: str
thumbnail: Optional["str"] = None
external_data = {"id": "123", "thumbnailUrl": "www.google.es"}
chat_message = ChatMessageAttachment(**external_data)
print(chat_message) # >>>id='123' thumbnail=None
In Pydantic, you can use aliases for this. In the code below you only need the Config allow_population_by_field_name if you also want to instantiate the object with the original thumbnail. If you only use thumbnailUrl when creating the object you don't need it:
from pydantic import BaseModel, Field
from typing import Optional
class ChatMessageAttachment(BaseModel):
id: str
thumbnail: Optional["str"] = Field(None, alias="thumbnailUrl")
class Config:
allow_population_by_field_name = True
external_data = {"id": "123", "thumbnailUrl": "www.google.es"}
chat_message = ChatMessageAttachment(**external_data)
print(chat_message)
# id='123' thumbnail='www.google.es
With allow_population_by_field_name you can also do:
external_data = {"id": "123", "thumbnail": "www.google.es"}
ChatMessageAttachment(**external_data)
# ChatMessageAttachment(id='123', thumbnail='www.google.es')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With