【问题标题】:how to serialize an array?如何序列化一个数组?
【发布时间】:2014-12-05 15:34:23
【问题描述】:

错误发生在控制器函数调用中。返回一个数据数组。我需要将此数组传递给模板。

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] 

【问题讨论】:

标签: python json django python-3.x


【解决方案1】:

正如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 对象时遇到了同样的问题,这很有帮助。

和平

【讨论】:

  • 我试图排除数据集日期时间类型的字段。问题依然存在
  • 你能告诉我们你做了哪些修改吗?
  • 我在答案中添加了代码,只是觉得把别人的功劳归功于别人的答案并不好。
  • 我编辑了我的问题。排除与日期相关的所有内容。但错误仍然存​​在
猜你喜欢
  • 2018-05-16
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
相关资源
最近更新 更多