Python: Query Dict to JSON

23,762

Solution 1

QueryDict class is a subclass of regular Python dictionary, except that it handles multiple values for a same key (see MultiValueDict implementation).

If you want to dump it to a string, just use json.dumps():

json.dumps(my_query_dict) 

There is also a relevant dict() method:

QueryDict.dict()

Returns dict representation of QueryDict.

Solution 2

Another way:

from django.http import QueryDict

# serialize
request.session["last_get_request"] = request.GET.urlencode()

# deserialize
last_get_request = QueryDict(request.session["last_get_request"])

Solution 3

If you want to handle multi values, you can do the following:

json.dumps({k: d.getlist(k) for k in d.keys()})

or use join for compactness:

json.dumps({k: ",".join(d.getlist(k)) for k in d.keys()})

or check if this is multi value, and only then show as list

 json.dumps({k: (d.getlist(k) if len(d.getlist(k)) > 1 else d[k]) for k in d.keys()})

Solution 4

I am using Python 2.7.13 and Django 1.11.2.You can get your data in a dictionary, so that you could access those data by using their related keys.

data = json.loads(request.GET.dict().keys()[0])

A block of code inside the function that I used to get the data. Output is also available at bottom. This will show the value of parts of the above statement.

But here I am using POST in place of GET as we are are posting data to the server.

So the above 1 line code is sufficient to get data as a dictionary in your case.

import json

# request.POST 
print "request.POST = ", request.POST
print type(request.POST),"\n"

# DICTIONARY
print "request.POST.dict() = ", request.POST.dict()
print type(request.POST.dict()), "\n"

# LIST ALL KEYS(here is only 1)
print "request.POST.dict().keys() = ", request.POST.dict().keys()
print type(request.POST.dict().keys()), "\n"

# UNICODE
print "request.POST.dict().keys()[0] = ", request.POST.dict().keys()[0]
print type(request.POST.dict().keys()[0]), "\n"

# GETTING THE ORIGINAL DATA(as Dictionary)
data = json.loads(request.POST.dict().keys()[0])    

# PRINTING DATA AND IT'S TYPE
print "json.loads(request.POST.dict().keys()[0]): ", data
print type(data), "\n"

# ITERATING OVER ITEMS in data dictionary
for key, value in data.iteritems():
    print key, value

Let's see the output,

request.POST = <QueryDict: {u'{"fname":"Rishikesh Agrawani","email":"[email protected]","contact":"7353787704","message":"Have a nice day."}': [u'']}>
<class 'django.http.request.QueryDict'> 

request.POST.dict() =  {u'{"fname":"Rishikesh Agrawani","email":"[email protected]","contact":"7353787704","message":"Have a nice day."}': u''}
<type 'dict'> 

request.POST.dict().keys() =  [u'{"fname":"Rishikesh Agrawani","email":"[email protected]","contact":"7353787704","message":"Have a nice day."}']
<type 'list'> 

request.POST.dict().keys()[0] =  {"fname":"Rishikesh Agrawani","email":"[email protected]","contact":"7353787704","message":"Have a nice day."}
<type 'unicode'> 

json.loads(request.POST.dict().keys()[0]):  {u'message': u'Have a nice day.', u'contact': u'7353787704', u'email': u'[email protected]', u'fname': u'Rishikesh Agrawani'}
<type 'dict'> 

message Have a nice day.
contact 7353787704
email [email protected]
fname Rishikesh Agrawani
Share:
23,762
d9120
Author by

d9120

Updated on April 07, 2021

Comments

  • d9120
    d9120 about 3 years

    I am trying to send some JSON to my django app in a query string by using encodeURIComponent() my server enpoint receives the data just fine as I can print it to the python console.

    print request.GET
    

    The output of the following line is in this format

    <QueryDict: {u'[my json array]': [u''}}>
    

    I want to convert this to JSON so I can use to get some information but I've tried using json.loads and other means of manipulating the data with no luck.

    My output should look like this

    [{u'something': something}, {u'something1': something2}, {u'something3': something3}]
    

    Any tips as to what I am doing wrong here?

  • d9120
    d9120 over 9 years
    Great that's exactly what I needed to understand.
  • dalore
    dalore over 7 years
    This won't work if you have multiple values for a key. You even mention MultiValueDict