blob: be15b34c8f21f7274d69bd8198920e4b05e3cdca (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
"""Custom json encoders for various purposes."""
import json
from uuid import UUID
from datetime import datetime
__ENCODERS__ = {
UUID: lambda obj: {"__type": "UUID", "__value": str(obj)},
datetime: lambda obj: {"__type": "DATETIME", "__value": obj.isoformat()}
}
class CustomJSONEncoder(json.JSONEncoder):
"""
A custom JSON encoder to handle cases where the default encoder fails.
"""
def default(self, obj):# pylint: disable=[arguments-renamed]
"""Return a serializable object for `obj`."""
if type(obj) in __ENCODERS__:
return __ENCODERS__[type(obj)](obj)
return json.JSONEncoder.default(self, obj)
__DECODERS__ = {
"UUID": UUID,
"DATETIME": datetime.fromisoformat
}
def custom_json_decoder(obj_dict):
"""Decode custom types"""
if "__type" in obj_dict:
return __DECODERS__[obj_dict["__type"]](obj_dict["__value"])
return obj_dict
|