【问题标题】:How to parse a nested json ajax object in Django views?如何在 Django 视图中解析嵌套的 json ajax 对象?
【发布时间】:2013-06-16 13:38:10
【问题描述】:

我需要提出如下请求:

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 对象的正确方法应该是什么?

【问题讨论】:

    标签: ajax django json


    【解决方案1】:

    您应该在发送数据之前使用 JSON.stringify() 对数据进行字符串化:

    $.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()解析了:

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

    【讨论】:

      【解决方案2】:

      您可能会发现这里的答案很有用:Reading multidimensional arrays from a POST request in Django

      【讨论】:

        【解决方案3】:

        您可以尝试查看django-SplitJSONWidget-form 并从中做出决定。

        【讨论】:

          猜你喜欢
          • 2017-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多