345 pass |
345 pass |
346 else: |
346 else: |
347 |
347 |
348 class CubicWebJsonEncoder(JSONEncoder): |
348 class CubicWebJsonEncoder(JSONEncoder): |
349 """define a simplejson encoder to be able to encode yams std types""" |
349 """define a simplejson encoder to be able to encode yams std types""" |
|
350 |
|
351 # _iterencode is the only entry point I've found to use a custom encode |
|
352 # hook early enough: .default() is called if nothing else matched before, |
|
353 # .iterencode() is called once on the main structure to encode and then |
|
354 # never gets called again. |
|
355 # For the record, our main use case is in FormValidateController with: |
|
356 # dumps((status, args, entity), cls=CubicWebJsonEncoder) |
|
357 # where we want all the entity attributes, including eid, to be part |
|
358 # of the json object dumped. |
|
359 # This would have once more been easier if Entity didn't extend dict. |
|
360 def _iterencode(self, obj, markers=None): |
|
361 if hasattr(obj, '__json_encode__'): |
|
362 obj = obj.__json_encode__() |
|
363 return JSONEncoder._iterencode(self, obj, markers) |
|
364 |
350 def default(self, obj): |
365 def default(self, obj): |
351 if isinstance(obj, datetime.datetime): |
366 if isinstance(obj, datetime.datetime): |
352 return obj.strftime('%Y/%m/%d %H:%M:%S') |
367 return obj.strftime('%Y/%m/%d %H:%M:%S') |
353 elif isinstance(obj, datetime.date): |
368 elif isinstance(obj, datetime.date): |
354 return obj.strftime('%Y/%m/%d') |
369 return obj.strftime('%Y/%m/%d') |