4

I need to make a request as follows:

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)
        }
    });

But in this way, the request.POST object is not organizing the companies into a nested json array. Instead it makes it into a 2D array as follows:

<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']}>

In this way, I feel hard to reorganize the companies into a list of objects. I checked some other questions, some people say we should do this:

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

And then use json.loads to parse the string back to a list of objects. But I am keep getting parsing error if I use codes like this:

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

or this:

company_array = json.load(StringIO(company_array))

So what should be the correct way to handle nested JSON object?

3 Answers 3

4

You should use JSON.stringify() to stringify your data before sending it:

$.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)
        }
    });

Then you can parse with json.loads() on the server side:

 data = json.loads(request.POST.get('data'))
Sign up to request clarification or add additional context in comments.

Comments

0

You might find the answers here useful: Reading multidimensional arrays from a POST request in Django

Comments

0

You can try look to django-SplitJSONWidget-form and get decision from it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.