I\'ve been searching for quite a while with no success. My project isn\'t using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model)
I've extended the JSON Encoder class written by dpatru to support:
Filtering properties - only properties with a verbose_name will be encoded into JSON
class DBModelJSONEncoder(json.JSONEncoder):
"""Encodes a db.Model into JSON"""
def default(self, obj):
if (isinstance(obj, db.Query)):
# It's a reference query (holding several model instances)
return [self.default(item) for item in obj]
elif (isinstance(obj, db.Model)):
# Only properties with a verbose name will be displayed in the JSON output
properties = obj.properties()
filtered_properties = filter(lambda p: properties[p].verbose_name != None, properties)
# Turn each property of the DB model into a JSON-serializeable entity
json_dict = dict([(
p,
getattr(obj, p)
if (not isinstance(getattr(obj, p), db.Model))
else
self.default(getattr(obj, p)) # A referenced model property
) for p in filtered_properties])
json_dict['id'] = obj.key().id() # Add the model instance's ID (optional - delete this if you do not use it)
return json_dict
else:
# Use original JSON encoding
return json.JSONEncoder.default(self, obj)