Trying to parse `request.body` from POST in Django

118,601

In Python 3.0 to Python 3.5.x, json.loads() will only accept a unicode string, so you must decode request.body (which is a byte string) before passing it to json.loads().

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['content']

In Python 3.6, json.loads() accepts bytes or bytearrays. Therefore you shouldn't need to decode request.body (assuming it's encoded in UTF-8, UTF-16 or UTF-32).

Share:
118,601

Related videos on Youtube

Zach
Author by

Zach

Updated on July 05, 2022

Comments

  • Zach
    Zach almost 2 years

    For some reason I cannot figure out why Django isn't handling my request.body content correctly.

    It is being sent in JSON format, and looking at the Network tab in Dev Tools shows this as the request payload:

    {creator: "creatorname", content: "postcontent", date: "04/21/2015"}
    

    which is exactly how I want it to be sent to my API.

    In Django I have a view that accepts this request as a parameter and just for my testing purposes, should print request.body["content"] to the console.

    Of course, nothing is being printed out, but when I print request.body I get this:

    b'{"creator":"creatorname","content":"postcontent","date":"04/21/2015"}'
    

    so I know that I do have a body being sent.

    I've tried using json = json.loads(request.body) to no avail either. Printing json after setting that variable also returns nothing.

  • Zach
    Zach about 9 years
    This solved my problem! And accessing the elements works like body['keyname']. Thank you very much.
  • Jimmy Obonyo Abor
    Jimmy Obonyo Abor about 8 years
    This was very insightfull after countless nights
  • JChao
    JChao about 4 years
    thank you. i had the same problem only for one env and it turns out the problematic env is using py3.5
  • AnonymousUser
    AnonymousUser almost 3 years
    It didn't work, I get the same error.
  • Alasdair
    Alasdair almost 3 years
    @DerekPK please ask a new question and include your code and the full error message so that other users see it. I don’t think you’ll get help in the comments here.