utils.py
changeset 5328 c51e8f62652a
parent 5195 e8235b2789fc
parent 5320 848e92bb81cc
child 5385 b6e250dd7a7d
--- a/utils.py	Mon Apr 19 13:51:16 2010 +0200
+++ b/utils.py	Mon Apr 19 13:52:55 2010 +0200
@@ -318,6 +318,21 @@
 
     class CubicWebJsonEncoder(JSONEncoder):
         """define a simplejson encoder to be able to encode yams std types"""
+
+        # _iterencode is the only entry point I've found to use a custom encode
+        # hook early enough: .default() is called if nothing else matched before,
+        # .iterencode() is called once on the main structure to encode and then
+        # never gets called again.
+        # For the record, our main use case is in FormValidateController with:
+        #   dumps((status, args, entity), cls=CubicWebJsonEncoder)
+        # where we want all the entity attributes, including eid, to be part
+        # of the json object dumped.
+        # This would have once more been easier if Entity didn't extend dict.
+        def _iterencode(self, obj, markers=None):
+            if hasattr(obj, '__json_encode__'):
+                obj = obj.__json_encode__()
+            return JSONEncoder._iterencode(self, obj, markers)
+
         def default(self, obj):
             if isinstance(obj, datetime.datetime):
                 return obj.strftime('%Y/%m/%d %H:%M:%S')