Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydantic: How to parse JSON with custom property name

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
like image 302
Javi Avatar asked Dec 19 '25 16:12

Javi


1 Answers

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')
like image 88
Mark Avatar answered Dec 21 '25 05:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!