Unpack an object of non-standard type as part of JSON deserialization.
This function is designed to be passed as object_hook
parameter
to the json.loads
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149 | def json_unpack(obj: Dict[str, Any]) -> Any:
"""Unpack an object of non-standard type as part of JSON deserialization.
This function is designed to be passed as `object_hook` parameter
to the `json.loads` function. It provides support for object
types with custom (un)packing protocols registered as part of
declearn or using `declearn.utils.add_json_support`.
"""
# If 'obj' does not conform to JsonPack format, return it as-is.
if not isinstance(obj, dict) or (set(obj.keys()) != {"__type__", "dump"}):
return obj
# If 'obj' is JsonPack but spec is not found, warn before returning as-is.
spec = JSON_UNPACK.get(obj["__type__"])
if spec is None:
warnings.warn(
"JSON deserializer received a seemingly-packed object "
f"of name '{obj['__type__']}', the specifications for "
"which are unavailable.\nIt was returned as-is."
)
return obj
# Otherwise, use the recovered spec to unpack the object.
return spec.unpack(obj["dump"])
|