pythonjsonpydantic

Deserialize Aliased JSON using Pydantic


I am wanting to use the Pydantic (Version: 2.6.1) aliases so that I can use a Python keyword ('from') when creating JSON. I thought this would work:

from pydantic import BaseModel, Field

class TestModel(BaseModel):
    from_str: str = Field(serialization_alias="from")

test_obj = TestModel(from_str="John")
print("TestModel: ", test_obj)

test_json = test_obj.model_dump(by_alias=True)
print("Test JSON:", test_json)

deserialized_obj = TestModel.model_validate(test_json)
print("Deserialized: ", deserialized_obj)

This correctly loads into a dict with the right alias ('from'). But it gives me this error in the call to model_validate:

pydantic_core._pydantic_core.ValidationError: 1 validation error for TestModel
from_str
  Field required [type=missing, input_value={'from': 'John'}, input_type=dict]

I thought it would also use the serialization alias when converting back to a TestModel, but it doesn't seem so. I do need it to be able to round-trip. Any help is appreciated.

I have tried fiddling with validation_alias as well, but then I get issues when calling model_dump.


Solution

  • I was able to 'fix' this by setting up the class as follows:

    class TestModel(BaseModel):
        model_config = ConfigDict(populate_by_name=True)
        from_str: str = Field(alias="from")
    

    Where populate_by_name allows you to access the class variable via it's name, but serialization and validation use the alias.