2013-06-19 60 views
3

我需要做的請求如下:如何在Django視圖中解析嵌套的json ajax對象?

var url="http://127.0.0.1:8080/simulate/"; 
    $.ajax({ 
     url: url, 
     type: 'POST', 
     data:{ student_num:10, 
       company_num:10, 
       students:"", 
       csrfmiddlewaretoken:'{{csrf_token}}', 
       companies:[{weight:10},{weight:11},{weight:9}] 
      }, 
     success: function(data, textStatus, xhr) { 
      var text=xhr.responseText 
      console.log(text) 
     } 
    }); 

但這種方式,在request.POST對象不是組織companies到嵌套JSON數組。相反,它使得它成爲一個二維數組如下:

<QueryDict: {u'student_num': [u'10'], u'students': [u''], u'companies[2][weight]': [u'9'], u'companies[1][weight]': [u'11'], u'company_num': [u'10'], u'companies[0][weight]': [u'10'], u'csrfmiddlewaretoken': [u'RpLfyEnZaU2o4ExxCVSJkTJ2ws6WoPrs']}> 

這樣,我覺得很難的companies重組爲對象的列表。我查了一些其他問題,有的人說我們應該這樣做:

companies:"[{weight:10},{weight:11},{weight:9}]" 

然後用json.loads解析字符串返回到對象的列表。但我不斷收到解析錯誤,如果我用這樣的代碼:

company_array = request.POST['company_array'] 
company_array = json.loads(company_array) 

或本:

company_array = json.load(StringIO(company_array)) 

那麼應該怎麼處理嵌套的JSON對象的正確方法是什麼?

回答

2

您應該使用JSON.stringify()發送之前將字符串化您的數據:

data = json.loads(request.POST.get('data')) 

$.ajax({ 
     url: url, 
     type: 'POST', 
     data: { data: JSON.stringify({ student_num:10, 
       company_num:10, 
       students:"", 
       csrfmiddlewaretoken:'{{csrf_token}}', 
       companies:[{weight:10},{weight:11},{weight:9}] 
      }) }, 
     success: function(data, textStatus, xhr) { 
      var text=xhr.responseText 
      console.log(text) 
     } 
    }); 

然後你就可以在服務器端與json.loads()解析