在我看来,为什么这样做:
results = []
results.append({'status':1})
results.append({'bookmarks':[]})
simplejson.dumps(results)
# produces: []
而这不是:
from myapp.models import Bookmark
results = []
results.append({'status':1})
results.append({'bookmarks':Bookmark.objects.all()})
# fails with exception saying: [] is not JSON serializable
完全堆栈跟踪
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
答案 0 :(得分:2)
不使用simplejson
来序列化django对象,而是使用s erialization provided by django.
使用参考表格链接,您可以:
from django.core import serializers
data = serializers.serialize("json", Bookmark.objects.all())
答案 1 :(得分:1)
我在等待Burhan Khalid将他的评论转变为答案,但由于他没有,我会这样做。
使用simplejson.dumps(list(Bookmark.objects.all()))
使其正常工作