forked from statemindio/vyzzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_encoders.py
30 lines (26 loc) · 850 Bytes
/
json_encoders.py
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
import json
from decimal import Decimal
class ExtendedEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return {
"_type": "Decimal",
"value": str(obj)
}
if isinstance(obj, bytes):
return {
"_type": "bytes",
"value": obj.hex()
}
return super().default(obj)
class ExtendedDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
super().__init__(object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
if '_type' not in obj:
return obj
if obj['_type'] == 'Decimal':
return Decimal(obj['value'])
if obj['_type'] == 'bytes':
return bytes.fromhex(obj["value"])
return obj