【问题标题】:Passing JSONified object to back-end in Django?将 JSONified 对象传递到 Django 中的后端?
【发布时间】:2019-04-13 17:24:30
【问题描述】:

我试图将在 js 中创建的对象转换为 JSON,然后在 Django 中传递给我的后端。

首先我列出一个列表:

function get_account_info(){
    var account_list = [];
    $('.card').each(function(e){
        var account = [];
        account.push($(this).find('.name').val());
        account.push($(this).find('.username').val());
        account.push($(this).find('.password').val());

        if(account[0] != null){
            account_list.push(account);
        }
    })
    return account_list;
}

然后我尝试发布它:

var account_info_json = JSON.parse(get_account_info());
        $.ajax({
            type:'POST',
            url:'/create_new_group/create_group/',
            data:{
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                account_info: account_info_json,
            } ,
            success:function(data){
                    if(data.status == 1){
                            //success!
                            console.log('Success!')
                    }
                    else if(data.status == 2){
                            //failed
                            console.log('Failed!')
                    }
            }

这就是我在 views.py 中 print(json.dumps(request.POST)) 得到的结果

{"csrfmiddlewaretoken": "token_data_is_here", "account_info": "[[\"1111111\",\"1111111\",\"1111111\"],[\"222222\",\"222222\",\"222222\"]]"}

我只能像搅拌一样访问这些数据,而不是 JSON。我怎样才能使它像 JSON 一样访问它?

【问题讨论】:

    标签: javascript jquery json ajax django


    【解决方案1】:

    所有的数据在发送之前都会被转换成字符串,所以对于django你需要先将字符串转换成json。

    从字符串转换为json:

    import json
    str = json.loads(json_data)
    

    从字符串中获取json:

    import json
    json_data = json.loads(str)
    

    在您的情况下,您需要先将字符串转换为 json,然后才能在 python 中将其作为字典访问

    希望对你有帮助!!

    【讨论】:

      【解决方案2】:

      你已经先反序列化了 json 字符串:

      import json
      account_info = json.loads(request.POST['account_info'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多