Skip to content

Instantly share code, notes, and snippets.

@pplante
Created January 24, 2010 04:54
Show Gist options
  • Save pplante/285017 to your computer and use it in GitHub Desktop.
Save pplante/285017 to your computer and use it in GitHub Desktop.
# Copyright (c) 2010, Philip Plante of EndlessPaths.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def to_json(data, sub_documents=False):
import copy, datetime, time
from mongoengine import Document, ObjectIdField
def _convert_to_json(data):
struct = {}
ignore = ['_id', 'password']
for k in data:
if k in ignore: continue
value = data[k]
if sub_documents and hasattr(value, "__class__") and issubclass(value.__class__, Document):
struct[k] = _convert_to_json(value)
elif isinstance(value, datetime.datetime):
struct[k] = int(time.mktime(value.timetuple()) + value.microsecond/1e6)
elif isinstance(value, (unicode, str)):
struct[k] = value
return struct
return _convert_to_json(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment