-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonEncoder.py
More file actions
85 lines (61 loc) · 2.15 KB
/
JsonEncoder.py
File metadata and controls
85 lines (61 loc) · 2.15 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Custom json encoder & decoder classes
"""
import re
import json
from datetime import datetime
from decimal import Decimal, ROUND_UP
import arrow
# extend the json.JSONEncoder class
from MyClass import MyClass
class JSONEncoder(json.JSONEncoder):
# overload method default
def default(self, obj):
# Match all the types you want to handle in your converter
if isinstance(obj, datetime):
return arrow.get(obj).isoformat()
elif isinstance(obj, Decimal):
return float(Decimal(obj).quantize(Decimal("0.01"), ROUND_UP))
elif isinstance(obj, MyClass):
return JSONEncoder().encode({
"value1": obj.value_1,
"value2": obj.value_2
})
# Call the default method for other types
return json.JSONEncoder.default(self, obj)
class JSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
# handle your custom classes
if isinstance(obj, dict):
if "value1" in obj and "value2" in obj:
print(obj)
return MyClass(obj.get("value_1"), obj.get("value_2"))
# handling the resolution of nested objects
if isinstance(obj, dict):
for key in list(obj):
obj[key] = self.object_hook(obj[key])
return obj
if isinstance(obj, list):
for i in range(0, len(obj)):
obj[i] = self.object_hook(obj[i])
return obj
# resolving simple strings objects
# dates
if isinstance(obj, str):
obj = self._extract_date(obj)
return obj
@staticmethod
def _extract_date(value):
# iso format
if re.search(
r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)*\+[0-9]{2}:[0-9]{2}$",
value,
):
value = arrow.get(value).datetime
return value
def json_encode(data):
return JSONEncoder().encode(data)
def json_decode(string):
return JSONDecoder().decode(string)