Reading JSON Data With Django (Posted on April 13th, 2013)

While working on an application I ran in to an issue reading data from a request so I figured I'd share.

I'd say about 99% of the time when you're reading data from a Django request you're either using request.GET or request.POST. I ran into an issue where an app was sending JSON data through an AJAX request via POST. However, Django's request.POST wasn't picking it up which had me kind of confused. My next step was just to print out the request variable but that proved ineffective as well. The reason for this is that my data was hiding in a somewhat hidden property of the request object called body. The body property actually will allow you to read the body of the raw HTTP request. This is the preferred method for reading non-form data.

So if you're doing something like:

      type: "POST",
      contentType: "application/json",
      url: "/info",
      data: { first_name: "Max", status: "blogging" },
      dataType: "json"

Your data is hiding in request.body["first_name"] and request.body["status"] respectively.

Tags: Django