To serialize models, add a custom json encoder as in the following python:
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from django.utils import simplejson
class jsonEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, db.Model):
return dict((p, getattr(obj, p))
for p in obj.properties())
elif isinstance(obj, users.User):
return obj.email()
else:
return simplejson.JSONEncoder.default(self, obj)
# use the encoder as:
simplejson.dumps(model, cls=jsonEncoder)
This will encode:
- a date as as isoformat string (per this suggestion),
- a model as a dict of its properties,
- a user as his email.
To decode the date you can use this javascript:
function decodeJsonDate(s){
return new Date( s.slice(0,19).replace('T',' ') + ' GMT' );
} // Note that this function truncates milliseconds.
Note: Thanks to user pydave who edited this code to make it more readable. I had originally had used python's if/else expressions to express jsonEncoder
in fewer lines as follows: (I've added some comments and used google.appengine.ext.db.to_dict
, to make it clearer than the original.)
class jsonEncoder(simplejson.JSONEncoder):
def default(self, obj):
isa=lambda x: isinstance(obj, x) # isa(<type>)==True if obj is of type <type>
return obj.isoformat() if isa(datetime.datetime) else \
db.to_dict(obj) if isa(db.Model) else \
obj.email() if isa(users.User) else \
simplejson.JSONEncoder.default(self, obj)