【问题标题】:django simplejson [] is not JSON serializabledjango simplejson [] 不是 JSON 可序列化的
【发布时间】:2013-04-29 20:19:04
【问题描述】:

在我看来,为什么会这样:

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

【问题讨论】:

  • simplejson.dumps(list(Bookmark.objects.all()))

标签: django django-views simplejson


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    不要使用simplejson 序列化django 对象,而是使用serialization provided by django.

    参考表格链接,您可以:

    from django.core import serializers
    data = serializers.serialize("json", Bookmark.objects.all())
    

    【讨论】:

    • 实际上我必须制作一个自定义 json 对象,而不是只转储模型。并且文档对此并不清楚。
    • @ishaq,但你的问题并没有这么说。您正在尝试序列化Bookmark.objects.all()
    • @Rohan 是序列化比 json 快得多或有任何特定原因
    猜你喜欢
    • 2011-01-16
    • 2017-06-18
    • 1970-01-01
    • 2018-09-12
    • 2013-05-23
    • 2015-02-24
    • 2019-12-27
    • 2014-10-23
    • 2019-06-17
    相关资源
    最近更新 更多