2014-09-13 46 views
0

這是我在django 1.6中的代碼(正常運行) 我升級到了django 1.7。 首先simplejson depraated:我將simplejson更改爲json,但我總是收到相同的錯誤 不是json可序列化。DJANGO升級錯誤:不是JSON可序列化

任何想法?

瀏覽:

def request_to_json(request):  
    post_data = request.body 
    json_data = simplejson.loads(post_data) 
    return json_data 

def receiver(request): 
    try: 
     json_data = request_to_json(request) 
     user_id=json_data['user_id']; 
     site_id=json_data['site_id']; 
    # A variable to return to the app 
     response = 'Ok' 

    except: 
     response = sys.exc_info()[0] 

    return HttpResponse(simplejson.dumps(response)) 

錯誤

TypeError at /views/receiver/ 
<class 'TypeError'> is not JSON serializable 
Request Method: POST 
Request URL: http://localhost:8000/views/receiver/ 
Django Version: 1.7 
Exception Type: TypeError 
Exception Value:  
<class 'TypeError'> is not JSON serializable 
Exception Location: C:\Python34\lib\json\encoder.py in default, line 173 
Python Executable: C:\Python34\python.EXE 
Python Version: 3.4.1 
Python Path:  
['C:\\workspace-eclipse\\IndoorPositioning', 
'C:\\Python34\\lib\\site-packages\\setuptools-5.4.2-py3.4.egg', 
'C:\\Windows\\system32\\python34.zip', 
'C:\\Python34\\DLLs', 
'C:\\Python34\\lib', 
'C:\\Python34', 
'C:\\Python34\\lib\\site-packages'] 
Server time: Sat, 13 Sep 2014 12:18:36 +0200 

回答

0

您的異常處理程序拋出異常。您試圖將整個異常對象序列化爲json以返回給用戶。相反,得到異常的字符串表示,並返回:

def receiver(request): 
    try: 
     ... 
    except: 
     response = "%s" % sys.exc_info()[0] 
    return HttpResponse(simplejson.dumps(response)) 

(這不是直接返回內部異常消息一個好主意,你應該嘗試和專門捕獲異常,並返回一個用戶友好的消息,而不是的實際例外)

如果你想看爲什麼你在代碼中得到一個異常,你需要允許異常被引發。擺脫try .. catch塊,你會看到實際異常正在與問候的request_to_json功能

通過它的外觀提出,問題是,你正在試圖序列the entire body of the request

post_data = request.body 

simplejson不喜歡

+0

所有我現在得到的是:「」 – 2014-09-13 10:53:35

+0

我的問題是,爲什麼JSON沒有負載爲JSON .. – 2014-09-13 10:55:02

+0

除外: response =「錯誤」它返回錯誤 – 2014-09-13 10:55:43