Reputation: 17751
When I serialize a list of objects with a custom __get__
method, __get__
is not called and the raw (unprocessed by custom __get__
) value from __set__
is used. How does Python's json
module iterate over an item?
Note: if I iterate over the list before serializing, the correct value returned by __get__
is used.
Upvotes: 1
Views: 219
Reputation: 1966
From the Python 3.1.2 documentation (re-formatted for viewing here but otherwise unedited):
json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, **kw)
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
So your __get__
function should be passed as default=yourcustomjsonencoder.__get__
or something like that? Just a thought. I could be way off (and probably am), but it's an idea at least.
Upvotes: 0
Reputation: 38247
It checks whether the object is certain values, or isinstances of list, tuple, or dicts...
It provides a method for what to do if all this fails, and documents how to do this:
import simplejson
class IterEncoder(simplejson.JSONEncoder):
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return simplejson.JSONEncoder.default(self, o)
simplejson.dumps(YourObject,cls=IterEncoder)
Upvotes: 1