Skip to main content
 首页 » 编程设计

python之如何序列化一个数组

2025年05月04日13lyj

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

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 

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

和平