How to Serialize and Deserialize JSON Event Payloads in Python

Define an EventPayload class with custom to_json and from_json methods to convert event objects to JSON strings and back, using datetime parsing.

Easy Python 3.9+ Aug 9, 2026 Streaming & messaging 12 views 0 copies

Python code

46 lines
Python 3.9+
import json
from datetime import datetime


class EventPayload:
    def __init__(self, event_id, event_type, timestamp, data):
        self.event_id = event_id
        self.event_type = event_type
        self.timestamp = timestamp
        self.data = data

    def to_json(self):
        return json.dumps({
            "event_id": self.event_id,
            "event_type": self.event_type,
            "timestamp": self.timestamp.isoformat(),
            "data": self.data
        })

    @classmethod
    def from_json(cls, json_str):
        payload = json.loads(json_str)
        return cls(
            event_id=payload["event_id"],
            event_type=payload["event_type"],
            timestamp=datetime.fromisoformat(payload["timestamp"]),
            data=payload["data"]
        )


if __name__ == "__main__":
    original = EventPayload(
        event_id="evt_001",
        event_type="user_signup",
        timestamp=datetime(2024, 1, 15, 10, 30, 0),
        data={"username": "alice", "plan": "pro"}
    )

    serialized = original.to_json()
    print("Serialized:", serialized)

    deserialized = EventPayload.from_json(serialized)
    print("Deserialized event_id:", deserialized.event_id)
    print("Deserialized event_type:", deserialized.event_type)
    print("Deserialized timestamp:", deserialized.timestamp)
    print("Deserialized data:", deserialized.data)

Output

stdout
Serialized: {"event_id": "evt_001", "event_type": "user_signup", "timestamp": "2024-01-15T10:30:00", "data": {"username": "alice", "plan": "pro"}}
Deserialized event_id: evt_001
Deserialized event_type: user_signup
Deserialized timestamp: 2024-01-15 10:30:00
Deserialized data: {'username': 'alice', 'plan': 'pro'}

How it works

The to_json method uses json.dumps to convert the payload into a JSON string, explicitly serializing the datetime object to ISO format with isoformat(). The from_json classmethod uses json.loads to parse the string back into a dictionary, then converts the timestamp string back to a datetime object using fromisoformat. This approach ensures the timestamp is preserved with full precision across serialization. The pattern is a straightforward way to handle custom objects in JSON without relying on external libraries.

Common mistakes

  • Forgetting to convert datetime to string before serializing, causing TypeError
  • Not handling missing keys when deserializing, leading to KeyError
  • Using json.load instead of json.loads for string input
  • Omitting isoformat/fromisoformat conversion, resulting in loss of timestamp formatting

Variations

  1. Use dataclasses with a custom encoder/decoder for a more declarative approach.
  2. Use marshmallow or pydantic for automatic serialization with validation.

Real-world use cases

  • Publishing events to a message queue like Kafka or SQS with JSON-encoded payloads.
  • Consuming and reconstructing event objects in a stream processing pipeline for analytics.
  • Storing event logs in JSON format for replay or debugging in an event-sourced system.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Streaming & messaging

Related tutorials and quizzes for this topic.