0

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
4

2 回答 2

2

不要使用simplejsonfor 序列化 django 对象,而是使用 django提供的序列化。

通过参考链接,您可以执行以下操作:

from django.core import serializers
data = serializers.serialize("json", Bookmark.objects.all())
于 2013-05-06T05:55:37.297 回答
1

我一直在等待 Burhan Khalid 将他的评论变成答案,但既然他没有,我会的。

使用simplejson.dumps(list(Bookmark.objects.all()))使它工作

于 2013-06-12T07:22:21.163 回答