如何将请求数据转换为json或dict格式



从客户端,我通过ajax post接收一些数据。数据类型为json格式。

function sendProjectBaseInfo() {
    prj = {
        id : $('#id').val(),
        email : $('#email').val(),
        title : $('#title').val(),
    }
    $.ajax({
        url: '/prj/',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: prj,
        success: function(result) {
            alert(result.Result)
        }
    });
}

在得到json数据后,我尝试转换为json或dict格式。转换为json。我是这样写的:

import json
def post(self, request):
    if request.is_ajax():
        if request.method == 'POST':
            json_data = json.loads(request.data)
            print('Raw Data : %s'%request.body)
    return HttpResponse('OK!')

在上面的情况下,我得到了500内部服务器错误。

所以我写了下面这样的工作来解决这个错误。

import json
def post(self, request):
    if request.is_ajax():
        if request.method == 'POST':
            data = json.dumps(request.data)
            print('Raw Data : %s'%request.body)
    return HttpResponse('OK!')

毕竟我也犯了同样的错误。所以我正在调查所要求的数据。

import json
def post(self, request):
    if request.is_ajax():
        if request.method == 'POST':
            print('Raw Data : %s'%request.body)
    return HttpResponse('OK!')

打印输出为:

Raw Data : b'{"id":"1","email":"jason@test.co","title":"TEST"}'

我该如何克服这种情况?

请求字节(数据类型(的形式处理数据,因此首先我们需要将其转换为字符串格式。然后您可以将其转换成json格式

import json
def post(self,request):
   if request.is_ajax():
     if request.method == 'POST':
        json_data = json.loads(str(request.body, encoding='utf-8'))
        print(json_data)
   return HttpResponse('OK!')

您必须得到TypeError: the JSON object must be str, not 'bytes'异常。(是Python 3吗?(

如果是,那么在json.loads:.decode(encoding='UTF-8')之前尝试此操作这是因为,响应体是byte类型的,如果注意输出字符串开头的小b

if request.method == 'POST':
       json_data = json.loads(request.body.decode(encoding='UTF-8'))
       print('Raw Data : %s' % json_data)
       return HttpResponse('OK!')
$.ajax({
    url: '/prj/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: prj, #### YOUR ERROR IS HERE
    success: function(result) {
        alert(result.Result)
    }
});

您需要在js中将数据转换为字符串。

在js代码中执行以下操作

data: JSON.stringify(prj)

最新更新