##// END OF EJS Templates
improvements for extended json serializer
marcink -
r2160:3754ee8a beta
parent child Browse files
Show More
@@ -27,6 +27,7
27 import os
27 import os
28 import datetime
28 import datetime
29 import functools
29 import functools
30 import decimal
30 from rhodecode import __platform__, PLATFORM_WIN
31 from rhodecode import __platform__, PLATFORM_WIN
31
32
32 #==============================================================================
33 #==============================================================================
@@ -34,20 +35,47 from rhodecode import __platform__, PLAT
34 #==============================================================================
35 #==============================================================================
35
36
36
37
38 def _is_aware(value):
39 """
40 Determines if a given datetime.time is aware.
41
42 The logic is described in Python's docs:
43 http://docs.python.org/library/datetime.html#datetime.tzinfo
44 """
45 return (value.tzinfo is not None
46 and value.tzinfo.utcoffset(value) is not None)
47
48
37 def _obj_dump(obj):
49 def _obj_dump(obj):
38 """
50 """
39 Custom function for dumping objects to JSON
51 Custom function for dumping objects to JSON, if obj has __json__ attribute
52 or method defined it will be used for serialization
40
53
41 :param obj:
54 :param obj:
42 """
55 """
43 DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
56
44 DATE_FORMAT = "%Y-%m-%d"
45 if isinstance(obj, complex):
57 if isinstance(obj, complex):
46 return [obj.real, obj.imag]
58 return [obj.real, obj.imag]
59 # See "Date Time String Format" in the ECMA-262 specification.
60 # some code borrowed from django 1.4
47 elif isinstance(obj, datetime.datetime):
61 elif isinstance(obj, datetime.datetime):
48 return obj.strftime(DATETIME_FORMAT)
62 r = obj.isoformat()
63 if obj.microsecond:
64 r = r[:23] + r[26:]
65 if r.endswith('+00:00'):
66 r = r[:-6] + 'Z'
67 return r
49 elif isinstance(obj, datetime.date):
68 elif isinstance(obj, datetime.date):
50 return obj.strftime(DATE_FORMAT)
69 return obj.isoformat()
70 elif isinstance(obj, decimal.Decimal):
71 return str(obj)
72 elif isinstance(obj, datetime.time):
73 if _is_aware(obj):
74 raise ValueError("JSON can't represent timezone-aware times.")
75 r = obj.isoformat()
76 if obj.microsecond:
77 r = r[:12]
78 return r
51 elif isinstance(obj, set):
79 elif isinstance(obj, set):
52 return list(obj)
80 return list(obj)
53 elif isinstance(obj, OrderedDict):
81 elif isinstance(obj, OrderedDict):
General Comments 0
You need to be logged in to leave comments. Login now