【问题标题】:is not JSON serializable不是 JSON 可序列化的
【发布时间】:2013-04-26 12:29:50
【问题描述】:

我有以下列表视图

import json
class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return json.dumps(self.get_queryset().values_list('code', flat=True))

但我收到以下错误:

[u'ae', u'ag', u'ai', u'al', u'am', 
u'ao', u'ar', u'at', u'au', u'aw', 
u'az', u'ba', u'bb', u'bd', u'be', u'bg', 
u'bh', u'bl', u'bm', u'bn', '...(remaining elements truncated)...'] 
is not JSON serializable

有什么想法吗?

【问题讨论】:

  • 什么是国家型号?
  • 回溯是什么?
  • 换行是否有效:return json.dumps(list(self.get_queryset().values_list('code', flat=True)))
  • 添加列表时出现'str' object has no attribute 'status_code' 错误
  • 回溯就像["ae", "ag", "ai", "al", "am", "ao", "ar", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bg", "bh", "bl", "bm", "bn", "bo", "bq", "br", "bs", "bt", "by", "bz", "ca", "ch", "ck", "cl", "cm", "cn", "co"]

标签: python django json


【解决方案1】:

值得注意的是QuerySet.values_list()方法实际上并没有返回一个列表,而是一个django.db.models.query.ValuesListQuerySet类型的对象,为了保持Django惰性求值的目标,即生成“列表”所需的DB查询在评估对象之前不会实际执行。

不过,有点恼人的是,这个对象有一个自定义的__repr__ 方法,使它在打印出来时看起来像一个列表,所以并不总是很明显该对象不是真正的列表。

问题中的异常是由于自定义对象无法在 JSON 中序列化,因此您必须先将其转换为列表,然后...

my_list = list(self.get_queryset().values_list('code', flat=True))

...然后您可以使用...将其转换为 JSON

json_data = json.dumps(my_list)

您还必须将生成的 JSON 数据放在 HttpResponse 对象中,该对象 apparently 应该有一个 Content-Typeapplication/json,并带有...

response = HttpResponse(json_data, content_type='application/json')

...然后你可以从你的函数中返回。

【讨论】:

    【解决方案2】:
    class CountryListView(ListView):
         model = Country
    
        def render_to_response(self, context, **response_kwargs):
    
             return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 
    

    解决了问题

    mimetype 也很重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-07
      • 2019-07-05
      • 2016-08-03
      • 1970-01-01
      • 2017-10-24
      • 2016-09-19
      • 2016-08-02
      • 2019-02-08
      相关资源
      最近更新 更多