Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2693

Pydantic field JSON alias simply does not work

I need to specify a JSON alias for a Pydantic object. It simply does not work.

from pydantic import Field
from pydantic.main import BaseModel


class ComplexObject(BaseModel):
    for0: str = Field(None, alias="for")


def create(x: int, y: int):
    print("was here")
    co = ComplexObject(for0=str(x * y))
    return co


co = create(x=1, y=2)
print(co.json(by_alias=True))

The output for this is {"for" : null instead of {"for" : "2"}

Is this real? How can such a simple use case not work?

Upvotes: 3

Views: 5610

Answers (2)

Lucas Wiman
Lucas Wiman

Reputation: 11257

You can add the allow_population_by_field_name=True value on the Config for the pydantic model.

>>> class ComplexObject(BaseModel):
...     class Config:
...         allow_population_by_field_name = True
...     for0: str = Field(None, alias="for")
...
>>>
>>> def create(x: int, y: int):
...     print("was here")
...     co = ComplexObject(for0=str(x * y))
...     return co
...
>>>
>>> co = create(x=1, y=2)
was here
>>> print(co.json(by_alias=True))
{"for": "2"}
>>> co.json()
'{"for0": "2"}'
>>> co.json(by_alias=False)
'{"for0": "2"}'
>>> ComplexObject.parse_raw('{"for": "xyz"}')
ComplexObject(for0='xyz')
>>> ComplexObject.parse_raw('{"for": "xyz"}').json(by_alias=True)
'{"for": "xyz"}'
>>> ComplexObject.parse_raw('{"for0": "xyz"}').json(by_alias=True)
'{"for": "xyz"}'

Upvotes: 2

Sin4wd
Sin4wd

Reputation: 76

You need to use the alias for object initialization. ComplexObject(for=str(x * y)) However for cannot be used like this in python, because it indicates a loop! You can use it like this : co = ComplexObject(**{"for": str(x * y)})

Upvotes: 6

Related Questions