天天看點

datetime.date(2014, 4, 25) is not JSON serializable# 背景# 解決方法

# 背景

接口期望傳回json格式資料,但資料存儲在mysql中,先将mysql的資料轉為dict,然後将dict轉為json格式,然後就報這個錯誤了的,原因就是時間格式轉換問題

# 解決方法

1. 建立這麼一個方法

def date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        raise TypeError      

2. 然後這樣轉換:

json.dumps(people.as_dict(), default=date_handler)      
people.as_dict()是将mysql資料轉為dict格式

      

雖千萬人,吾往矣!