不是JSON可序列化 [英] is not JSON serializable

查看:190
本文介绍了不是JSON可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下ListView

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

但是我收到以下错误:

[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

任何想法?

推荐答案

p>我会添加一个稍微更详细的答案。

I'll add a slightly more detailed answer.

值得注意的是, QuerySet.values_list() 方法实际上不返回列表,而是 django.db.models.query.ValuesListQuerySet ,为了维护Django的懒惰评估的目标,即生成列表所需的数据库查询实际上不会被执行,直到对象被评估为止。

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.

尽管如此,这个对象有一个自定义的 __ repr __ 方法,使其在打印时看起来像一个列表,所以并不总是很明显,对象不是真正的列表。

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.

问题中的异常是由于自定义对象无法在JSON中序列化的事实,所以你必须首先将它转换成一个列表,... ...

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

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

...那么你可以将它转换成JSON与...

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

json_data = json.dumps(my_list)

您还必须将生成的JSON数据放在一个 HttpResponse 对象,其中显然是,应该有一个内容类型 application / json ,with ...

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

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

...您可以从您的功能返回。

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

这篇关于不是JSON可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆