Pydantic field JSON alias simply does not work

Question:

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?

Asked By: Jenia Ivanov

||

Answers:

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)})

Answered By: Sin4wd

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"}'
Answered By: Lucas Wiman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.