2

I have a very simple view that receives an ajax request containing a javascript object. The jquery request looks like this:

$.get(URL, {'kwargs': {test: 1}}, function(data){//whatever})

The problem is, request.GET now contains a rather strange key and looks like this:

{'kwargs[test]': [1]}

How can I successfully decode this? As a side note, it is impossible to know the key (test) beforehand

The expected format obtained is a python dict that looks like the one in the request.

I've tried:

request.GET.get('kwargs', None)

And I'd expect this as a result:

{'test': 1}

However, I get None, as the real key is 'kwargs[test]'

EDIT

I know I could use some kind of regex to accomplish this, but it feels as 'reinventing the wheel', as this use case is not that rare

1 Answer 1

5

I would recommend using JSON when communicating back and forth between the server and client for this type of situation. JSON is meant to handle these types of nested structures in a uniform manner.

Take a look at using the jQuery $.getJSON functionality, http://api.jquery.com/jquery.getjson/

The following is an example of how this structure would look...

Javscript

var request_data = {kwargs: {test: 1}};
$.getJSON(URL, {data: JSON.stringify(request_data)}, function(data){//whatever})

Django

import json
def your_view(request):
    my_json = json.loads(request.GET['data'])

Doing this will allow you to parse the request which contains JSON data into a variable of your choice (my_json). Once you assign your variable with the results of json.loads(), you will now have a python object containing the parsed requested JSON data and you will be able to manipulate your object accordingly.

>>> my_json['kwargs']
{u'test': 1}
Sign up to request clarification or add additional context in comments.

4 Comments

request.body seems to be an empty bytestring .. I'm using django 1.7
Do you have any clue on that? I've followed the $.getJSON scheme and I'm getting something in request.GET
Yup you are right. request.body doesn't get populated for 'GET' requests. I'll update my answer with more relative information.
managed to make it work with a mixture of JSON.stringify and $.get.. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.