Tags

a JSON REST trick

12:45pm on Dec 21, 2012

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
[RSS] [atom]
Tags