Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a nested json ajax object in Django views?

Tags:

json

ajax

django

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?

like image 253
Yitong Zhou Avatar asked Sep 07 '25 05:09

Yitong Zhou


1 Answers

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'))
like image 152
arthur.sw Avatar answered Sep 10 '25 00:09

arthur.sw