Вопрос

in my view, why does this work:

results = []
results.append({'status':1})
results.append({'bookmarks':[]})
simplejson.dumps(results)
# produces: []

and this doesn't:

from myapp.models import Bookmark
results = []
results.append({'status':1})
results.append({'bookmarks':Bookmark.objects.all()})
# fails with exception saying: [] is not JSON serializable

completely stack trace follows

Traceback:
File "/Users/Ishaq/Projects/github/bookmarks/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Ishaq/Projects/github/bookmarks/bookmarks/views.py" in index
  9.   return HttpResponse(simplejson.dumps(Bookmark.objects.all()), mimetype='application/json');
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
  231.         return _default_encoder.encode(obj)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
  201.         chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in iterencode
  264.         return _iterencode(o, 0)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
  178.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /conferences/
Exception Value: [] is not JSON serializable
Это было полезно?

Решение 2

I was waiting for Burhan Khalid to turn his comment into an answer, but since he hasn't, I would.

using simplejson.dumps(list(Bookmark.objects.all())) made it work

Другие советы

Instead of using simplejson for serialize django objects, use serialization provided by django.

With reference form the link, you can do:

from django.core import serializers
data = serializers.serialize("json", Bookmark.objects.all())
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top