Can't return JSON object?

2,010 views
Skip to first unread message

John Allen

unread,
May 26, 2011, 10:17:48 PM5/26/11
to MongoEngine Users
So I'm trying to return a JSON object for a project. I've spent a few
hours trying to get Django just returning the JSON.

Heres the view that we've been working with:

def json(request, first_name):
user = User.objects.all()
#user = User.objects.all().values()
result = simplejson.dumps(user, default=json_util.default)
return HttpResponse(result)


Here's my model:

class User(Document):
gender = StringField( choices=['male', 'female', 'Unknown'])
age = IntField()
email = EmailField()
display_name = StringField(max_length=50)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
location = StringField(max_length=50)
status = StringField(max_length=50)
hideStatus = BooleanField()
photos = ListField(EmbeddedDocumentField('Photo'))
profile =ListField(EmbeddedDocumentField('ProfileItem'))
allProfile = ListField(EmbeddedDocumentField('ProfileItem')) #only
return for your own profile


This is what it's returning:

[<User: User object>, <User: User object>] is not JSON serializable


Any thoughts on how I can just return the JSON?

Technium

unread,
May 27, 2011, 5:20:29 AM5/27/11
to MongoEngine Users
I have a method I use for a generic JSON output option for all pages,
although I'm sure it is far from perfect. It handles mongoengine
objects and queries as well as evaluating groupby generators. Note
that you might not want to include ObjectID references in the way I do
as my use is purely internal and doesn't care about security.

def encode_model(self, obj):
if isinstance(obj, (mongoengine.Document,
mongoengine.EmbeddedDocument)):
out = dict(obj._data)
for k,v in out.items():
if isinstance(v, ObjectId):
out[k] = str(v)
elif isinstance(obj, mongoengine.queryset.QuerySet):
out = list(obj)
elif isinstance(obj, types.ModuleType):
out = None
elif isinstance(obj, groupby):
out = [ (g,list(l)) for g,l in obj ]
else:
raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj),
str(obj))

return out

Use:
response = simplejson.dumps(data, default=encode_model)

Aniket Zamwar

unread,
Nov 15, 2013, 4:44:20 PM11/15/13
to mongoeng...@googlegroups.com
Hi,

I am trying to use authenticate by defining a model which extends the User of mongoengine. 
But when I am trying to do auth.login(user, request) it gives this error given above. The auth I am using here is django auth. Because mongonengine does not have some API for login.

Jan Schrewe

unread,
Nov 15, 2013, 10:14:07 PM11/15/13
to mongoeng...@googlegroups.com
Hey,

Django 1.6 doesn't use python's own pickle protocol any longer for storing the session data but uses JSON now. Mongo db uses almost JSON to store it's data but not quite JSON. That is where your error comes from. You can use the following serialiser which will work fine:

from bson import json_util

class JSONSerializer(object):
    """
    Simple wrapper around json to be used in signing.dumps and
    signing.loads.
    """
    def dumps(self, obj):
        return json_util.dumps(obj, separators=(',', ':')).encode('utf-8')

    def loads(self, data):
        return json_util.loads(data.decode('utf-8'))

And add the following setting to your settings.py:

SESSION_SERIALIZER = 'my_project.session_serializer.JSONSerializer'

Obviously you need to adjust the import path.

There is already at least one pull request for mongoengine to include the serialiser and fix the docs, so you hopefully don't need to worry about providing your own serialiser forever.


--
You received this message because you are subscribed to the Google Groups "MongoEngine Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoengine-us...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages