-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
43 lines (34 loc) · 1018 Bytes
/
common.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
31
32
33
34
35
36
37
38
39
40
41
42
43
import json
from base64 import b64encode
class ReprType(object):
"""An object that should be inherited from to avoid being converted to a
JSON dict."""
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
if isinstance(o, ReprType):
return repr(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)