-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomjson.py
More file actions
executable file
·35 lines (30 loc) · 1.06 KB
/
customjson.py
File metadata and controls
executable file
·35 lines (30 loc) · 1.06 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
"""
Custom JSON Encoder to encode any arbitrary generator, iterator, closure or
functor. This is really frustrating to have to include everywhere because this
should just be the default behavior of the library.
"""
from json import JSONEncoder
from decimal import Decimal
class ExtJsonEncoder(JSONEncoder):
'''
Extends ``simplejson.JSONEncoder`` by allowing it to encode any
arbitrary generator, iterator, closure or functor.
'''
def default(self, c):
# Handles generators and iterators
if hasattr(c, '__iter__'):
return [i for i in c]
# Handles closures and functors
if hasattr(c, '__call__'):
return c()
# Handles precise decimals with loss of precision to float.
# Hack, but it works
if isinstance(c, Decimal):
return float(c)
return simplejson.JSONEncoder.default(self, c)
def dumps(*args):
'''
Shortcut for ``ExtJsonEncoder.encode()``
'''
return ExtJsonEncoder(sort_keys=False, ensure_ascii=False,
skipkeys=True).encode(*args)