KOB
KOB

Reputation: 4545

Custom JSON encoder not working with nested model

I am trying to create a custom JSON encoding for a nested Pydantic model. I have simplified the problem to the following example:

from pydantic import BaseModel


class SubModel(BaseModel):
    name: str
    short_name: str


class TestModel(BaseModel):
    sub_model: SubModel

    class Config:
        json_encoders = {SubModel: lambda s: s.short_name}


model = TestModel(sub_model=SubModel(name="Sub Model", short_name="SM"))

print(model)
print(model.json())

I am expecting the final line to output:

{"sub_model": "SM"}

But instead I am getting the output as if I never even defined my own json_encoders:

{"sub_model": {"name": "Sub Model", "short_name": "SM"}}

How can I correctly define a JSON encoder for another Pydantic model?

Upvotes: 2

Views: 1703

Answers (2)

Christian Kasim Loan
Christian Kasim Loan

Reputation: 422

I ran into the same problem. What worked for me is setting the JSON encoders on the global BaseConfig instead of the class


from pydantic import BaseConfig
BaseConfig.json_encoders = {
    MyClass: lambda v: v.as_str(),
}


Reference: https://github.com/pydantic/pydantic/issues/2277#issuecomment-764010272

Upvotes: 1

Mornie
Mornie

Reputation: 21

There's nothing wrong with the json_encoder you specified. You just need to add models_as_dict=False to the json() method to override the default dict-like serialization:

print(model.json(models_as_dict=False))

See https://pydantic-docs.helpmanual.io/usage/exporting_models/#serialising-self-reference-or-other-models for the reference.

Upvotes: 2

Related Questions