pythongoogle-app-enginesimplejson

How to serialize db.Model objects to json?


When using

from django.utils import simplejson

on objects of types that derive from db.Model it throws exceptions. How to circumvent this?


Solution

  • Since I could not find an appropriate solution I wrote my own, which is not exactly a JSON serializer, but a Javascript serializer

    from google.appengine.ext import db
    from google.appengine.api.datastore_types import *
    
    def dumpStr(obj):
        return "'" + obj + "'"
    
    def dumps(obj):
        if isinstance(obj, str):
            return dumpStr(obj)
        elif obj == None:
            return None
        elif isinstance(obj, list):
            items = [];
            for item in obj:
                items.append(dumps(item))
            return '[' + ','.join(items) + ']'
        elif isinstance(obj, datetime.datetime):
            return "new Date('%s')" % obj.ctime()
        properties = [];
        for property in dir(obj):
            if property[0] != '_':
                value = obj.__getattribute__(property)
                valueClass = str(value.__class__)
                if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):
                    value = dumps(value)
                    if value != None:
                        properties.append("'" + property + "':" + value)
        if len(properties) == 0:
            return str(obj)
        else:
            return '{' + ','.join(properties) + '}'