2013-06-19 61 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()解析