Package grassyknoll :: Package serial :: Module JsonSerial
[hide private]

Source Code for Module grassyknoll.serial.JsonSerial

 1  """ 
 2  Code to convert to/from JSON and basic Python types. 
 3  """ 
 4   
 5  import simplejson 
 6  import datetime 
 7   
 8   
 9  MIMETYPES=set([ 
10      "application/json", 
11      "text/javascript", 
12      "application/x-javascript" # stdlib.mimetypes returns this for foo.js 
13  ]) 
14 -class DateTimeAwareJSONEncoder(simplejson.JSONEncoder):
15 """ 16 L{simplejson.JSONEncoder} subclass that knows how to encode date/time types 17 18 Per http://www.json.org/json.js, "official" JSON dates are 19 U{ISO Dates<http://en.wikipedia.org/wiki/Iso_date>}. 20 """ 21 22 DATE_FORMAT = "%Y-%m-%d" 23 TIME_FORMAT = "%H:%M:%S" 24
25 - def default(self, o):
26 if isinstance(o, datetime.datetime): 27 return o.strftime("%sT%s" % (self.DATE_FORMAT, self.TIME_FORMAT)) 28 elif isinstance(o, datetime.date): 29 return o.strftime(self.DATE_FORMAT) 30 elif isinstance(o, datetime.time): 31 return o.strftime(self.TIME_FORMAT) 32 else: 33 return super(DateTimeAwareJSONEncoder, self).default(o)
34
35 -def dumps(obj, **kwargs):
36 return simplejson.dumps(obj, cls=DateTimeAwareJSONEncoder, **kwargs)
37 38 # NOTE We can't use loads' C{object_hook} to implement a corresponding loader, 39 # since that only gets called for B{objects} (ie, dicts), not individual 40 # values. Subclassing JSONDecoder is possible, but painful. L{Norman}s are a 41 # much better solution. 42 loads=simplejson.loads 43