2015-10-05 354 views
0

從客戶端,我通過ajax post收到一些數據。數據類型是json格式。如何將請求數據轉換爲json或dict格式

function sendProjectBaseInfo() { 

    prj = { 
     id : $('#id').val(), 
     email : $('#email').val(), 
     title : $('#title').val(), 
    } 

    $.ajax({ 
     url: '/prj/', 
     type: 'POST', 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 
     data: prj, 
     success: function(result) { 
      alert(result.Result) 
     } 
    }); 
} 

得到json數據後,我嘗試轉換爲json或dict格式。 轉換爲json。我這樣寫:

import json 

def post(self, request): 
    if request.is_ajax(): 
     if request.method == 'POST': 
      json_data = json.loads(request.data) 
      print('Raw Data : %s'%request.body) 
    return HttpResponse('OK!') 

在上面的情況下,我得到500內部服務器錯誤。

所以我寫下如下來解決這個錯誤。

import json 

def post(self, request): 
    if request.is_ajax(): 
     if request.method == 'POST': 
      data = json.dumps(request.data) 
      print('Raw Data : %s'%request.body) 
    return HttpResponse('OK!') 

畢竟我得到了同樣的錯誤。所以我正在研究所要求的數據。

import json 

def post(self, request): 
    if request.is_ajax(): 
     if request.method == 'POST': 
      print('Raw Data : %s'%request.body) 
    return HttpResponse('OK!') 

打印出來是:

Raw Data : b'{"id":"1","email":"[email protected]","title":"TEST"}' 

我怎樣才能克服這種情況?

回答

0

您必須得到TypeError: the JSON object must be str, not 'bytes'例外。 (是Python3?)

如果是,那麼 嘗試在此之前json.loads.decode(encoding='UTF-8') 這是因爲,響應主體是byte型的,如果在輸出字符串的開頭通知小b

if request.method == 'POST': 
     json_data = json.loads(request.body.decode(encoding='UTF-8')) 
     print('Raw Data : %s' % json_data) 
     return HttpResponse('OK!') 
+0

對我不起作用以下。 – eachone

+0

@eachone:然後在這裏打印完整的錯誤跟蹤,否則我們將無法找出問題所在。 –

+0

我在哪裏可以得到錯誤信息?但是,我已經解決了這個錯誤。在客戶端,數據:JSON.stringfy(prj)。您的評論對我有幫助。 – eachone

0

請求處理數據中的字節(數據類型)的形式所以首先我們需要將它轉換成字符串格式,之後可以將其轉換爲json格式

import json 

def post(self,request): 
    if request.is_ajax(): 
    if request.method == 'POST': 
     json_data = json.loads(str(request.body, encoding='utf-8')) 
     print(json_data) 
    return HttpResponse('OK!') 
0
$.ajax({ 
    url: '/prj/', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    data: prj, #### YOUR ERROR IS HERE 
    success: function(result) { 
     alert(result.Result) 
    } 
}); 

您需要將您的數據轉換成字符串在JS。

不要在你的js代碼

data: JSON.stringify(prj) 
相關問題