8000 Appropriate replacement for json_encoders · Issue #6726 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content

Appropriate replacement for json_encoders #6726

@xmatthias

Description

@xmatthias

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

I used to have working code using json_encoders to encode and enforce datetime fields to an expected format.

With the removal of json_encoders - i'm now no longer sure how to accomplish this, as my model must be defined a bit vague intentionally.

in the below example, there's seemingly one datetime field - which i can probably easily convert with @field_serializer.

The problematic part is the data: List[Any] section - which can will be a list containing one or multiple datetimes (as well as multiple other types).

the expected output for data can be something around the following:

 [
    ['2017-11-26 08:50:00', 8.794e-05, 0, 1511686200000, None, None, None, None],
    ['2017-11-26 08:51:00', 8.794e-05, 0, 1511686200000, None, 'randomString', None, None]
    ['2017-11-26 08:51:00', 8.794e-05, 0, 1511686200000, None, None, None, '2017-11-26 08:50:00']
   # ....
]

in pydantic v1, json_encoders simply looked for all datetime types and serialized them as expected, but i see no real alternative for this in pydantic v2 without handling all serialization for the whole model (the actual model is a lot bigger than the below specified).

Example Code

from pydantic import BaseModel, ConfigDict

DATETIME_PRINT_FORMAT = '%Y-%m-%d %H:%M:%S'

class CustomData(BaseModel):
    columns: List[str]
    data: List[Any]
    last_analyzed: datetime

    # TODO[pydantic]: The following keys were removed: `json_encoders`.
    # Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
    model_config = ConfigDict(json_encoders={
        datetime: lambda v: v.strftime(DATETIME_PRINT_FORMAT),
    })


### Python, Pydantic & OS Version

```Text
pydantic version: 2.0.3
        pydantic-core version: 2.3.0 release build profile
                 install path: /home/xmatt/.pyenv/versions/3.11.4/envs/trade_3114/lib/python3.11/site-packages/pydantic
               python version: 3.11.4 (main, Jun 12 2023, 20:09:51) [GCC 13.1.1 20230429]
                     platform: Linux-6.4.3-arch1-1-x86_64-with-glibc2.37
     optional deps. installed: ['typing-extensions']

Might be related to #6375



Selected Assignee: @Kludex

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0