pynenc.serializer.json_serializer¶
Module Contents¶
Classes¶
Protocol for objects that support full round-trip JSON serialization. |
|
A custom JSON encoder that extends the default JSONEncoder to handle special object types. |
|
Implements the BaseSerializer for JSON serialization using the custom DefaultJSONEncoder. |
Functions¶
Recursively convert Enum instances to envelope dicts before encoding. |
|
Import a module and traverse a dotted qualname to find the class. |
|
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.ProtocolProtocol for objects that support full round-trip JSON serialization.
Implement both
to_json()andfrom_json()on your class.- Class:
DefaultJSONEncoderwill embed the class’s module and qualified name alongside the serialized data so that :class:JsonSerializercan 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.
- 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.JSONEncoderA 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_EXCEPTIONso they can be fully reconstructed.Objects implementing :class:
JsonSerializable— any object with ato_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
Noneand (’,’, ‘: ‘) 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:
Enum — serialized with module, qualname, and value for reconstruction.
Builtin Exception — serialized to
{ReservedKeys.ERROR: {type, args, message}}.Custom Exception — serialized to
{ReservedKeys.CLIENT_EXCEPTION: {module, qualname, args, message}}so that non-builtin exceptions (user-defined) can be fully round-tripped.JsonSerializable — any object that implements
to_json()is serialized by calling that method.All other types raise
TypeErrorwith 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.BaseSerializerImplements 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.