Skip to content

fix: serialize pydantic CloudEvent data that contains datetime values - #313

Open
eisen0419 wants to merge 1 commit into
cloudevents:mainfrom
eisen0419:fix/213-pydantic-json-datetime-data
Open

eisen0419 wants to merge 1 commit into
cloudevents:mainfrom
eisen0419:fix/213-pydantic-json-datetime-data

Conversation

@eisen0419

Copy link
Copy Markdown

Related Issue: Fixes #213

Type of change:

  • Bug fix (non-breaking change which fixes an issue)

Description:
Both Pydantic CloudEvent implementations (cloudevents.v1.pydantic.v2.event and cloudevents.v1.pydantic.v1.event, re-exported via cloudevents.v1.pydantic.CloudEvent) serialize structured JSON through cloudevents.v1.conversion.to_json, which delegates to stdlib json.dumps without applying Pydantic's JSON serializer to data. As a result, calling .json() or .model_dump_json() when data contains datetime (or other Pydantic-serializable types such as date, time, UUID, Decimal, or nested BaseModel instances) raised TypeError: Object of type datetime is not JSON serializable.

This change encodes non-binary data payloads with the corresponding Pydantic serializer prior to conversion.to_json while leaving top-level binary payloads (bytes, bytearray, memoryview) untouched so they continue to serialize as data_base64 per the CloudEvents JSON format specification:

  • Pydantic v2: encodes non-binary data via TypeAdapter(Any).dump_python(..., mode="json") while forwarding relevant SerializationInfo options (by_alias, exclude_unset, exclude_defaults, exclude_none, exclude_computed_fields, round_trip, serialize_as_any, polymorphic_serialization, context).
  • Pydantic v1: encodes non-binary data using the default encoder passed into Config.json_dumps (including custom json_encoders and .json(encoder=...)) while preserving outer json.dumps formatting arguments.
  • Envelope attributes (time RFC3339 formatting, null-attribute omission, extensions) and event.data in-memory values remain unchanged.

Pre-submission checklist:

  • I have read the CONTRIBUTING.md file.
  • I have signed off my commits using git commit --signoff.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have updated the documentation (README.md, CHANGELOG.md, etc.) as necessary.
  • I have run pre-commit and tox and all checks pass.
  • This pull request is ready to be reviewed.

.json() and model_dump_json() sent the payload through stdlib json.dumps, which rejects datetime and the other values Pydantic already knows how to encode.

Signed-off-by: eisen0419 <usetoken0419@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.json() unable to serialize datetime elements in data payload

1 participant