Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do JSON handler in Django

I want to get and parse json in django view.

Requst in template:

var values = {};
$("input[name^='param']").each(function() {
    values[$(this).attr("name")] = $(this).val();
});

$.ajax
({
    type: "POST",
    url: page,
    contentType: 'application/json; charset=utf-8',
    async: false,
    processData: false,
    data: $.toJSON(values),
    success: function (resp) {
        console.log(resp);

    }
});

In view:

import json
...
req = json.loads(request.body)
return HttpResponse(req)

It give me error:

the JSON object must be str, not 'bytes'

What I do wrong?

like image 214
bdhvevhvonof Avatar asked Sep 22 '14 07:09

bdhvevhvonof


People also ask

What is JSON response in Django?

JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.

How do I return a JSON response in Django?

The JsonResponse transforms the data you pass to it to a JSON string and sets the content type HTTP header to application/json . To return JSON data from a Django view you swap out the HttpResponse for JsonResponse and pass it the data that needs to be transformed to JSON.

How do I return a JSON response?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.


1 Answers

Most web framework consider string representation as utf-8, so bytes in Python 3 (like Django, and Pyramid). In python3 needs to decode('utf-8') for body in:

req = json.loads( request.body.decode('utf-8') )
like image 170
bdhvevhvonof Avatar answered Nov 15 '22 15:11

bdhvevhvonof