Alex Rivera | Logout

serializing result of a queryset with json raises error:

Asked 2011-07-16T20:43:36.317
12

I was trying to serialize a Python list but got errors that it's not serializable. Is there a limitation on serializing a list of Long integers?

>>> ids=p.values_list('id',flat=True)
>>> ids
[335L, 468L, 481L, 542L, 559L, 567L, 609L]
>>> import simplejson as json
>>> str=json.dumps(ids)

Traceback (most recent call last):
   File "<console>", line 1, in <module>
  File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\__ini
t__.py", line 265, in dumps
    return _default_encoder.encode(obj)
  File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 216, in encode
    chunks = list(chunks)
  File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 495, in _iterencode
    o = _default(o)
  File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 190, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [335L, 468L, 481L, 542L, 559L, 567L, 609L] is not JSON serializable
>>>
Edit
Report

1 Answer

2

The problem here is that values_list(), which is a django function (you probably should clarify this in your question) does not return a list.

>>> x = UserProfile.objects.values_list('employee_id', flat=True)
>>> type(x)
>>> <class 'django.db.models.query.ValuesListQuerySet'>

simplejson.dumps doesn't know how to serialize this object. So like @mac suggested, you need to typecast this return value to a list.

answered 2011-07-16T21:20:51.007

Your Answer