Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created June 19, 2012 14:47
Show Gist options
  • Save akhenakh/2954605 to your computer and use it in GitHub Desktop.
Save akhenakh/2954605 to your computer and use it in GitHub Desktop.
flask jsonify with support for MongoDB from tools import jsonify
try:
import simplejson as json
except ImportError:
try:
import json
except ImportError:
raise ImportError
import datetime
from bson.objectid import ObjectId
from werkzeug import Response
class MongoJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, ObjectId):
return unicode(obj)
return json.JSONEncoder.default(self, obj)
def jsonify(*args, **kwargs):
""" jsonify with support for MongoDB ObjectId
"""
return Response(json.dumps(dict(*args, **kwargs), cls=MongoJsonEncoder), mimetype='application/json')
@jessejohnson
Copy link

Awesome! Took me the whole night to get here, but thanks!

@pixelogik
Copy link

Great stuff, thx!

@erikhenrique
Copy link

Thx man!

@pixelogik
Copy link

Perfect, thx!

@mshettysubbaiah
Copy link

Saved my day!

@jdamasceno
Copy link

Thank you !
It worked like a charm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment