pynenc.serializer.json_serializer

Module Contents

Classes

JsonSerializable

Protocol for objects that support full round-trip JSON serialization.

DefaultJSONEncoder

A custom JSON encoder that extends the default JSONEncoder to handle special object types.

JsonSerializer

Implements the BaseSerializer for JSON serialization using the custom DefaultJSONEncoder.

Functions

_preprocess_for_json

Recursively convert Enum instances to envelope dicts before encoding.

_resolve_class

Import a module and traverse a dotted qualname to find the class.

_reconstruct_from_json

Recursively reconstruct typed objects from reserved-key envelopes.

Data

API

pynenc.serializer.json_serializer.TJsonSerializable

‘TypeVar(…)’

class pynenc.serializer.json_serializer.JsonSerializable[source]

Bases: typing.Protocol

Protocol for objects that support full round-trip JSON serialization.

Implement both to_json() and from_json() on your class.

Class:

DefaultJSONEncoder will embed the class’s module and qualified name alongside the serialized data so that :class:JsonSerializer can reconstruct the original object on deserialization.

Example::

from pynenc.serializer.json_serializer import JsonSerializable

class Money:
    def __init__(self, amount: float, currency: str) -> None:
        self.amount = amount
        self.currency = currency

    def to_json(self) -> dict:
        return {"amount": self.amount, "currency": self.currency}

    @classmethod
    def from_json(cls, data: dict) -> "Money":
        return cls(data["amount"], data["currency"])

Any task argument or return value that implements this protocol will be transparently serialized and deserialized when using :class:JsonSerializer.

to_json() Any[source]

Return a JSON-serializable representation of this object.

classmethod from_json(data: Any) Any[source]

Reconstruct an instance from the value returned by to_json.

class pynenc.serializer.json_serializer.DefaultJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.JSONEncoder

A custom JSON encoder that extends the default JSONEncoder to handle special object types.

This encoder handles:

  • Enums — serialized with module, qualname, and value for full round-trip reconstruction.

  • Builtin exceptions (e.g. ValueError) — serialized with type, args, and message under :attr:ReservedKeys.ERROR.

  • Custom (non-builtin) exceptions — serialized with module, qualname, args, and message under :attr:ReservedKeys.CLIENT_EXCEPTION so they can be fully reconstructed.

  • Objects implementing :class:JsonSerializable — any object with a to_json() method is serialized by calling that method. This is the recommended way for application code to make domain objects compatible with Pynenc’s JSON serializer without subclassing or patching the encoder.

Initialization

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float, bool or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (’,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (’,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(obj: Any) Any[source]

Overrides the default method to provide custom serialization logic.

Resolution order:

  1. Enum — serialized with module, qualname, and value for reconstruction.

  2. Builtin Exception — serialized to {ReservedKeys.ERROR: {type, args, message}}.

  3. Custom Exception — serialized to {ReservedKeys.CLIENT_EXCEPTION: {module, qualname, args, message}} so that non-builtin exceptions (user-defined) can be fully round-tripped.

  4. JsonSerializable — any object that implements to_json() is serialized by calling that method.

  5. All other types raise TypeError with a descriptive message including the object’s type and a truncated repr.

Parameters:

obj (Any) – The object to be serialized.

Returns:

A JSON-serializable representation of obj.

Raises:

TypeError – If the object is not serializable.

pynenc.serializer.json_serializer._preprocess_for_json(obj: Any) Any[source]

Recursively convert Enum instances to envelope dicts before encoding.

IntEnum and StrEnum subclasses are natively serializable by json, so JSONEncoder.default() is never called for them. This pre-pass ensures they get the same envelope treatment as regular Enums.

pynenc.serializer.json_serializer._resolve_class(module_name: str, qualname: str) type[source]

Import a module and traverse a dotted qualname to find the class.

pynenc.serializer.json_serializer._reconstruct_from_json(data: Any) pynenc.serializer.json_serializer.TJsonSerializable | Any[source]

Recursively reconstruct typed objects from reserved-key envelopes.

class pynenc.serializer.json_serializer.JsonSerializer[source]

Bases: pynenc.serializer.base_serializer.BaseSerializer

Implements the BaseSerializer for JSON serialization using the custom DefaultJSONEncoder.

This class provides methods to serialize and deserialize objects to and from JSON strings, with special handling for Python exceptions.

static serialize(obj: Any) str[source]

Serializes an object into a JSON string.

Enum instances (including IntEnum/StrEnum) are preprocessed into envelope dicts so they survive the round-trip.

Parameters:

obj (Any) – The object to serialize.

Returns:

A JSON string representation of ‘obj’.

static deserialize(obj: str) Any[source]

Deserializes a JSON string back into an object.

Recursively reconstructs objects from reserved-key envelopes (exceptions, JsonSerializable, Enum).

Parameters:

obj (str) – The JSON string to deserialize.

Returns:

The deserialized object.