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?
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.
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.
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.
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') )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With