如何序列化数组?
问题描述:
控制器功能调用发生错误。返回一组数据。我需要将这个数组传递给模板。如何序列化数组?
views.py:
def new_authors(request):
new_authors = UserProfile.get_new_authors_entries()
# UserProfile.get_new_authors_entries() retrun:
#[
# {
# 'id': 4,
# 'username': 'zzzzzz'
# },
# {
# 'id': 5,
# 'username': 'wwwwww'
# }
#]
return HttpResponse(json.dumps(new_authors), content_type='application/json')
,但我得到了以下错误消息:
File "/usr/lib/python3.4/json/encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable") TypeError: [{'id': 4, 'username': 'zzzzzz'}, {'id': 5, 'username': 'wwwwww'}] is not JSON serializable
models.py:
class UserProfile(User):
@classmethod
def get_new_authors_entries(self, cut_begin=0, cut_end=2):
return self.objects.filter(is_active=1, is_superuser=0).values('id', 'username')[cut_begin:cut_end]
答
由于这post建议,您可以使用默认参数json.dumps
来处理您的问题:
>>> dthandler = lambda obj: (
... obj.isoformat()
... if isinstance(obj, datetime.datetime)
... or isinstance(obj, datetime.date)
... else None)
>>> json.dumps(datetime.datetime.now(), default=dthandler)
'"2010-04-20T20:08:21.634121"'
我有同样的问题,序列化对象datetime
,这帮助。
和平
我认为这个问题来自尝试序列化'datetime'对象。如果是这样,[这可能有所帮助](http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python) – CoryKramer 2014-10-10 12:52:31
也请看看:https: //docs.djangoproject.com/en/dev/topics/serialization/ – Brandon 2014-10-10 12:53:25
你应该向我们展示get_new_authors_entries的确切功能。我怀疑它返回一个ValuesQuerySet,而不是一个字典。 – 2014-10-10 12:53:55