a JSON REST trick

December 21, 2012 @ 12:45

So I’m doing some REST stuff with SQLAlchemy classes, and I needed a simple way to dump the objects to JSON. This base class will convert an object to a dict, and has some options for funny fields and such.

You may (will) want to use a custom JSON encoder (see simplejson docs) to convert some of the data types, like datetime.datetime in particular.

It’s certainly not ideal, in particular the isinstance() call, but it works at the moment for what I’m doing.

class JsonObject(object):

    def __to_json__(self, exclude_fields = []):
        d = {}

        for prop in dir(self):
            if prop.startswith('_') or prop in exclude_fields:
                continue
            val = getattr(self, prop)

            # we want standard data, not instance methods and such
            if callable(val):
                continue
            if isinstance(val, (sqlalchemy.schema.MetaData, JsonObject)):
                continue

            # you can define a custom formatter for this data
            if hasattr(self, '__formatters__') and prop in self.__formatters__:
                d[prop] = self.__formatters__[prop](data)
            else:
                d[prop] = val
      
        return d