-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictify.py
35 lines (33 loc) · 1.2 KB
/
dictify.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
import datetime
import re
def dictify( data, includeInstanceMethods = False):
"""
Serializes a given python object and returns an object that is safe to be converted to a JSON string
Serializes the given data to a json serializable format.
1. ignores methods and instance methods
2. Serializes instance objects to a dictionary
3. Serializes recursivley on objects and iterable data structures
"""
#if class instance apply dictify on data.__dict__
cls = re.compile("<class .*>").match(str(type(data)))
if cls:
result = dictify(data.__dict__, includeInstanceMethods)
if includeInstanceMethods:
for attr in dir(data):
if not attr.startswith('__') and not attr.endswith('__') and attr not in result:
result[attr]= 'Instance Method'
return result
if type(data) in [datetime.datetime, datetime.date, datetime.time]:
return str(data)
dataType = re.compile("<type .*>").match(str(type(data)))
if dataType:
if not '__iter__' in dir(data):
return data
else:
if type(data) == dict:
result = {}
for key in data.keys():
result[key]=dictify(data[key], includeInstanceMethods)
return result
else:
return list([dictify(item, includeInstanceMethods) for item in data])