Python 不是 JSON 可序列化的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16336271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:20:06  来源:igfitidea点击:

is not JSON serializable

pythondjangojson

提问by tuna

I have the following ListView

我有以下列表视图

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))

But I get following error:

但我收到以下错误:

[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

Any ideas ?

有任何想法吗 ?

采纳答案by Aya

It's worth noting that the QuerySet.values_list()method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

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

Somewhat irritatingly, though, this object has a custom __repr__method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

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

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

问题中的异常是由于无法在 JSON 中序列化自定义对象这一事实引起的,因此您必须先将其转换为列表,使用...

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

...then you can convert it to JSON with...

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

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponseobject, which, apparently, should have a Content-Typeof application/json, with...

您还必须将生成的 JSON 数据放在一个HttpResponse对象中,该对象显然应该有一个Content-Typeof application/json,...

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

...which you can then return from your function.

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

回答by tuna

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") 

fixed the problem

解决了问题

also mimetype is important.

mimetype 也很重要。