-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_handler.py
51 lines (48 loc) · 1.45 KB
/
json_handler.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
44
45
46
47
48
49
50
51
import calendar
import datetime
import re
try:
import uuid
_use_uuid = True
except ImportError:
_use_uuid = False
from bson.dbref import DBRef
from bson.max_key import MaxKey
from bson.min_key import MinKey
from bson.objectid import ObjectId
from bson.timestamp import Timestamp
from bson.tz_util import utc
from geojson.mapping import Mapping
from geojson import Feature, FeatureCollection
_RE_TYPE = type(re.compile("foo"))
def handler(obj):
if isinstance(obj, ObjectId):
return {"$oid": str(obj)}
if isinstance(obj, DBRef):
return obj.as_doc()
if isinstance(obj, datetime.datetime):
# TODO share this code w/ bson.py?
return obj.isoformat() + 'Z'
if isinstance(obj, _RE_TYPE):
flags = ""
if obj.flags & re.IGNORECASE:
flags += "i"
if obj.flags & re.MULTILINE:
flags += "m"
return {"$regex": obj.pattern,
"$options": flags}
if isinstance(obj, MinKey):
return {"$minKey": 1}
if isinstance(obj, MaxKey):
return {"$maxKey": 1}
if isinstance(obj, Timestamp):
return {"t": obj.time, "i": obj.inc}
if _use_uuid and isinstance(obj, uuid.UUID):
return {"$uuid": obj.hex}
if isinstance(obj, Mapping):
return dict(obj)
if isinstance(obj, Feature):
return dict(obj)
if isinstance(obj, FeatureCollection):
return dict(obj)
raise TypeError("%r is not JSON serializable" % obj)