Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert request.get and request.post data to dictionary

I'm trying to convert request.GET and request.POST to dictionary I tried doing request.GET.dict() and json.dumps(request.GET). somehow it returns dict like structure. for eg: {'name': 'abc'}, but type of this dict is str

like image 840
Magnotta Avatar asked Dec 06 '25 14:12

Magnotta


1 Answers

I tried doing request.GET.dict() and json.dumps(request.GET). somehow it returns dict like structure. for eg: {'name': 'abc'}, but type of this dict is str.

That makes perfect sense, since json.dumps makes a JSON blob. Such JSON blob is always a string. With this statement.

request.GET is however already a dict. Indeed, it is a QueryDict [GitHub], and a QueryDict is a subclass of a MultiValuedDict [GitHub]. This is a subclass of the dict. So a QueryDict is a subclass of a dict.

You can obtain the dictionary by using the QueryDict.dict() [Django-doc] method, which will return a dictionary:

result = request.GET.dict()

and then for example create a JSON blob with that result:

json.dumps(request.GET.dict())

Here the last value in the querystring will be used if multiple ones are passed with the same key.

but that being said, usually it is not necessary to convert it to a dictionary in the first place.

like image 180
Willem Van Onsem Avatar answered Dec 09 '25 13:12

Willem Van Onsem