eachone
eachone

Reputation: 577

How can I convert request data to json or dict format

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

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:

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.

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":"[email protected]","title":"TEST"}'

How can I overcome this situation?

Upvotes: 2

Views: 25367

Answers (3)

Ahmed
Ahmed

Reputation: 3012

$.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.

Do the following in your js code

data: JSON.stringify(prj)

Upvotes: 0

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

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.

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

Upvotes: 4

Gaurav Jain
Gaurav Jain

Reputation: 1865

you must be getting TypeError: the JSON object must be str, not 'bytes' exception. (is it 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

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

Upvotes: 3

Related Questions