tags:

views:

93

answers:

2

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.

A: 

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)
MattH
actually, im already using a custom json encoder. its just being given the raw value, and not the result of `__get__`. any ideas?
Carson
Could you post an example of the object you are trying to serialize? From the way it looks to me at the moment, if you're using an encoder like this one, then the iterated objects will be passed in the list `chunks` to `"".join(chunks)`.
MattH
A: 

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.

Dustin