Skip to content

declearn.utils.json_pack

Pack an object of non-standard type for JSON serialization.

This function is designed to be passed as default parameter to the json.dumps function. It provides support for object types with custom (un)packing protocols registered as part of declearn or using declearn.utils.add_json_support.

Source code in declearn/utils/_json.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def json_pack(obj: Any) -> JsonPack:
    """Pack an object of non-standard type for JSON serialization.

    This function is designed to be passed as `default` parameter
    to the `json.dumps` function. It provides support for object
    types with custom (un)packing protocols registered as part of
    declearn or using `declearn.utils.add_json_support`.
    """
    spec = JSON_PACK.get(type(obj))
    if spec is None:
        raise TypeError(
            f"Object of type '{type(obj)}' is not JSON-serializable.\n"
            "Consider using `declearn.utils.add_json_support` to make it so."
        )
    return {"__type__": spec.name, "dump": spec.pack(obj)}