Skip to content

Instantly share code, notes, and snippets.

@JackStouffer
Created July 24, 2014 20:19
Show Gist options
  • Save JackStouffer/c0cf40e7f27e4fa941fa to your computer and use it in GitHub Desktop.
Save JackStouffer/c0cf40e7f27e4fa941fa to your computer and use it in GitHub Desktop.
Turn a Mongoengine object in a json-ible dictionary
def mongo_to_dict(obj):
""" Turn a mongoengine object into a jsonible python object
"""
return_data = []
if isinstance(obj, db.Document):
return_data.append(("id", str(obj.id)))
for field_name in obj._fields:
data = obj._data[field_name]
if isinstance(obj._fields[field_name], db.DateTimeField):
return_data.append((field_name, str(data.isoformat())))
elif isinstance(obj._fields[field_name], db.StringField):
return_data.append((field_name, str(data)))
elif isinstance(obj._fields[field_name], db.FloatField):
return_data.append((field_name, float(data)))
elif isinstance(obj._fields[field_name], db.IntField):
return_data.append((field_name, int(data)))
elif isinstance(obj._fields[field_name], db.ListField):
return_data.append((field_name, data))
elif isinstance(obj._fields[field_name], db.EmbeddedDocumentField):
return_data.append((field_name, mongo_to_dict(data)))
elif isinstance(obj._fields[field_name], db.ObjectIdField):
return_data.append((field_name, str(data)))
else:
print type(obj._fields[field_name])
return dict(return_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment