Missing json_encoders in v2 - Any similar functionality #6697
Replies: 7 comments 1 reply
-
Facing a similar problem in #6726 |
Beta Was this translation helpful? Give feedback.
-
I believe the new approach would be to use the functional serializers |
Beta Was this translation helpful? Give feedback.
-
Yes, functional serializers are the proper solution, but we've just added support (albeit with a deprecation warning) back in #6811 |
Beta Was this translation helpful? Give feedback.
-
@samuelcolvin probably makes sense to have somewhere an example that translates from the v1 to v2 because it is not super clear from the documentation. |
Beta Was this translation helpful? Give feedback.
-
I'd be keen to get an official example as well. Our use case is fairly simple, in that our pydantic models have some pandas dataframes as attritubtes, so we have Given this applies to all dataframe attritbutes without having to write out the field name for all of them, its very handy. But with the new approach, I'm not sure if I should be using |
Beta Was this translation helpful? Give feedback.
-
How eventually have you rewritten your code? |
Beta Was this translation helpful? Give feedback.
-
I got this from the test written in the feature support PR : class Model(BaseModel):
x: timedelta
y: Decimal
z: date
model_config = ConfigDict(
json_encoders={timedelta: lambda v: f'{v.total_seconds():0.3f}s', Decimal: lambda v: 'a decimal'}
) |
Beta Was this translation helpful? Give feedback.
-
This is just a small example of my use case. I have a RootModel which I use across my project. I have to json encode this at one place to avoid duplication of code (DRY).
I can see that json_encoders are removed in Pydantic v2. So how do I achieve the same in v2. This is very important to me since I have around 20 to 30 different models which needs this functionality
Beta Was this translation helpful? Give feedback.
All reactions