2

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?

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Pydantic not having a proper API Reference doc is extremely painful and makes it really difficult to discover features like this. Especially when the user hides information like this behind complicated headings like "Serialising self-reference or other models" that most people aren't likely to read, thinking that it's not relevant in this situation because it's not a "self-reference".
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.