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

时间:2021-07-12 06:34:48

From the client side, I receive some data by ajax post. The data type is json format.

从客户端,我通过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)
        }
    });
}

After got the json data, I try to convert to json, or dict format. To convert to json. I wrote like this:

获得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!')

in case of above, I got 500 Internal server Error.

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

So I wrote like below to work around this error.

所以我写下面的代码来解决这个错误。

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!')

After all I got the same error. So I was look into the requested data.

毕竟我得到了同样的错误。所以我查看了请求的数据。

import json

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

Print out is :

打印出来的是:

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

How can I overcome this situation?

我怎样才能克服这种情况?

3 个解决方案

#1


1  

request handles the data in the form of bytes(data type) so first we need to convert it into string format, after you can convert it into json format.

请求以字节(数据类型)的形式处理数据,因此首先我们需要将其转换为字符串格式,然后才能将其转换为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!')

#2


0  

you must be getting TypeError: the JSON object must be str, not 'bytes' exception. (is it Python3?)

你必须得到TypeError:JSON对象必须是str,而不是'bytes'异常。 (是Python3吗?)

if yes, then try this before json.loads: .decode(encoding='UTF-8') this is because, the response body is of byte type, if notice small b in the beginning of output string

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

if request.method == 'POST':
       json_data = json.loads(request.body.decode(encoding='UTF-8'))
       print('Raw Data : %s' % json_data)
       return HttpResponse('OK!')

#3


0  

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

You will need to convert your data into string in your js.

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

Do the following in your js code

在您的js代码中执行以下操作

data: JSON.stringify(prj)

#1


1  

request handles the data in the form of bytes(data type) so first we need to convert it into string format, after you can convert it into json format.

请求以字节(数据类型)的形式处理数据,因此首先我们需要将其转换为字符串格式,然后才能将其转换为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!')

#2


0  

you must be getting TypeError: the JSON object must be str, not 'bytes' exception. (is it Python3?)

你必须得到TypeError:JSON对象必须是str,而不是'bytes'异常。 (是Python3吗?)

if yes, then try this before json.loads: .decode(encoding='UTF-8') this is because, the response body is of byte type, if notice small b in the beginning of output string

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

if request.method == 'POST':
       json_data = json.loads(request.body.decode(encoding='UTF-8'))
       print('Raw Data : %s' % json_data)
       return HttpResponse('OK!')

#3


0  

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

You will need to convert your data into string in your js.

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

Do the following in your js code

在您的js代码中执行以下操作

data: JSON.stringify(prj)