不是JSON可序列化

编程入门 行业动态 更新时间:2024-10-11 01:17:58
本文介绍了不是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可序列化

本文发布于:2023-11-25 09:16:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!