-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonParser.py
53 lines (39 loc) · 1.2 KB
/
jsonParser.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
52
53
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple MongoDB parser for output pretty JSON with ObjectID support
"""
try:
import json
except ImportError:
import simplejson as json
import datetime
Parser = None
# Limit import
__all__ = ["Parser"]
class DefaultJsonParser(json.JSONEncoder):
""" Create a basic JSON parser instance """
def default(self, obj):
""" Output data """
# Printer for datetime object
if isinstance(obj, datetime.datetime):
return obj.isoformat()
# Switch to default handler
return json.JSONEncoder.default(self, obj)
# Setting parser to default one
Parser = DefaultJsonParser
try:
import bson.objectid
# Import was a success, we add Mongo ObjectId compatibility
class MongoJsonParser(DefaultJsonParser):
""" Specific MongoDB manage ObjectId """
def default(self, obj):
""" Output data """
# Printer for MongoDB ObjectId
if isinstance(obj, bson.objectid.ObjectId):
return str(obj)
return DefaultJsonParser.default(self, obj)
# Switch parser to new mongo supported one
Parser = MongoJsonParser
except ImportError:
pass