Django request Post json

穿精又带淫゛_ 提交于 2019-11-30 11:32:57

You're posting JSON, which is not the same as form-encoded data. You need to get the value of request.body and deserialize it:

data = json.loads(request.body)
custom_decks = data['custom_decks']

As I was having problems with getting JSON data from HttpRequest directly with the code of the other answer:

data = json.loads(request.body)
custom_decks = data['custom_decks']

error:

the JSON object must be str, not 'bytes'

Here is an update of the other answer for Python version >3:

json_str=((request.body).decode('utf-8'))
json_obj=json.loads(json_str)

Regarding decode('utf-8'), as mention in:

RFC 4627:

"JSON text shall be encoded in Unicode. The default encoding is UTF-8."

I attached the Python link referred to this specific problem for version >3.

http://bugs.python.org/issue10976

Since HttpRequest has a read() method loading JSON from request is actually as simple as:

def post(self, request, *args, **kwargs):
    import json
    data = json.load(request)
    return JsonResponse(data=data)

If you put this up as a view, you can test it and it'll echo any JSON you send back to you.

python 3.6 and django 2.0 :

post_json = json.loads(request.body)
custom_decks = post_json.get("custom_decks")

json.loads(s, *, encoding=None,...)

Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.

From python 3.6 NO need request.body.decode('utf-8') .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!