简体   繁体   English

如何在Django中将嵌套的JSON对象转换为Python

[英]How to convert nested JSON object to Python in Django

I'm working on a Django application that posts data to the server. 我正在将数据发布到服务器的Django应用程序上工作。

Here is the Python snippet: 这是Python代码段:

def save(request):
    if request.method != 'POST':
        return HttpResponse('Illegal Request')

    print(request.POST.get('dataObj'))

    return JsonResponse({'status':200})

JQuery on the client side: 客户端上的JQuery:

function submitQuoationClicked()
{
    dataObj = getQuotationInJSON()
    console.log(dataObj)
    token = $("input[name=csrfmiddlewaretoken]").val()
    $.ajax({
     type:"POST",
     url:"/quotations/save",
     data: {
        'csrfmiddlewaretoken': token,
        'dataObj' : dataObj,
     },
     success: function(data){
        if(data.status === 200)
            console.log("Good Work Falak!") //TODO Remove this line, FOR DEBUGGING ONLY
     }
});

function getQuotationInJSON()
{

    var data = {};

    data['title'] = $("#title").val()
    data['companyName'] = $("#company").val()
    data['addressLine1'] = $("#addressLine1").val()
    data['addressLine2'] = $("#addressLine2").val()
    data['city'] = $("#city").val()
    data['country'] = $("#country").val()

    data['date'] = $("#date").val()
    data['number'] = $("#number").val()
    data['validTill'] = $("#validTill").val()


    sections = getItemsData();
    data['sections'] = sections
    return data
}

function getItemsData()
{
    sections = []
    $("tr[id^='section']").each(function(index, element)
    {
        sectionId = $(element).attr('id').split('section')[1]
        name = $(element).find("#sectionName" + sectionId).val()
        section = {}
        section['name'] = name

        //Now get section items
        rowElems = $(".section" + sectionId)
        rows = []
        $(rowElems).each(function(index, row){
        if($(row).attr('id').indexOf('itemRow')>=0)
        {
            description = $(row).find("#description").val()
            quantity = $(row).find("#quantity").val()
            unitPrice = $(row).find("#unitPrice").val()
            margin = $(row).find("#margin").val()

            if(quantity!="" && unitPrice!="" && description!="" && margin!="")
            {
                row = {}
                row['description'] = description
                row['quantity'] = quantity
                row['unitPrice'] = unitPrice
                row['margin'] = margin

                rows.push(row)
            }
        }
    });

    section['items'] = rows;
    sections.push(section)
    });
    return sections
}

The JSON object is a quotation which has some basic details. JSON对象是一个报价,其中包含一些基本细节。 It has some sections, each section has a name and a list of items in that section. 它包含一些节,每个节都有一个名称和该节中的项目列表。 Each item has some properties. 每个项目都有一些属性。 But print(request.body) return 'None'. 但是print(request.body)返回'None'。 If I print(request.body), its prints the following text: 如果我打印(request.body),它会打印以下文本:

b'csrfmiddlewaretoken=ph8NQTz5uDtYaTSI5bDVAcdQ0MQtPrYWMMpIFOYP5eqD8urd2wtPRtxypBSnNg1J&dataObj%5Btitle%5D=Title&dataObj%5BaddressLine1%5D=&dataObj%5BaddressLine2%5D=&dataObj%5Bcity%5D=&dataObj%5Bcountry%5D=&dataObj%5Bdate%5D=&dataObj%5Bnumber%5D=&dataObj%5BvalidTill%5D=&dataObj%5Bsections%5D%5B0%5D%5Bname%5D=S1&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bdescription%5D=Hey&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bquantity%5D=2&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5BunitPrice%5D=9&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bmargin%5D=0' b'csrfmiddlewaretoken = ph8NQTz5uDtYaTSI5bDVAcdQ0MQtPrYWMMpIFOYP5eqD8urd2wtPRtxypBSnNg1J&dataObj%5Btitle%5D =标题&dataObj%5BaddressLine1%5D =&dataObj%5BaddressLine2%5D =&dataObj%5Bcity%5D =&dataObj%5Bcountry%5D =&dataObj%5Bdate%5D =&dataObj%5Bnumber%5D =&dataObj%5BvalidTill% 5D =&dataObj%5Bsections%5D%5B0%5D%5Bname%5D = S1&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bdescription%5D = Hey&dataObj%5Bsections%5D%5BBits 5D%5B0%5D%5Bquantity%5D = 2&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5BunitPrice%5D = 9&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0 5Bmargin%5D = 0'

I tried to get 'dataObj' from the request.POST.get('dataObj) but it returns None. 我试图从request.POST.get('dataObj)获取'dataObj',但它返回None。

What is causing the problem? 是什么原因引起的?

使用Ajax发出POST请求时,请在请求中添加以下标头:

ContentType:application/x-www-form-urlencoded

Your keys in the POST are going to look like this: request.POST.get('dataObj[title]') 您在POST中的键将如下所示: request.POST.get('dataObj[title]')

See the answer on this question for details on how to handle the JSON in request.body Where's my JSON data in my incoming Django request? 有关如何处理request.body JSON的详细信息,请参见此问题的答案。 传入的Django请求中的JSON数据在哪里?

I have figured out the problem. 我已经解决了问题。 The object that I was trying to pass were Javascript objects, not JSON. 我尝试传递的对象是Javascript对象,而不是JSON。 So the keys were appearing not in the expected format. 因此,密钥显示的格式不是预期的。 So, I had to use JSON.stringify() method. 因此,我不得不使用JSON.stringify()方法。

Here is the updated code: //Ajax call modified to: 这是更新的代码:// Ajax调用修改为:

$.post("/quotations/save", {csrfmiddlewaretoken: token, 
       data: JSON.stringify(dataObj)}, //Edited here
       function(result){
   if(result.status===200){
       console.log("Good Work Falak!")
   }
   else
   {
       console.log("Failed!")
   }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM