2014-10-10 68 views
2

控制器功能調用發生錯誤。返回一組數據。我需要將這個數組傳遞給模板。如何序列化數組?

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] 
+0

我認爲這個問題來自嘗試序列化'datetime'對象。如果是這樣,[這可能有所幫助](http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python) – CoryKramer 2014-10-10 12:52:31

+0

也請看看:https: //docs.djangoproject.com/en/dev/topics/serialization/ – Brandon 2014-10-10 12:53:25

+2

你應該向我們展示get_new_authors_entries的確切功能。我懷疑它返回一個ValuesQuerySet,而不是一個字典。 – 2014-10-10 12:53:55

回答

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,這幫助。

和平

+0

我試圖排除數據集類型datetime的字段。問題仍然存在 – dert 2014-10-10 13:35:51

+0

你能告訴我們你準確做出了哪些修改嗎? – Oscar 2014-10-10 15:02:44

+0

我在我的答案中添加了代碼,只是認爲用別人的答案來評價並不好。 – Oscar 2014-10-10 15:20:11