简体   繁体   中英

Python: Query Dict to JSON

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?

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.

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":"rishikesh0014051992@gmail.com","contact":"7353787704","message":"Have a nice day."}': [u'']}>
<class 'django.http.request.QueryDict'> 

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

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

request.POST.dict().keys()[0] =  {"fname":"Rishikesh Agrawani","email":"rishikesh0014051992@gmail.com","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'rishikesh0014051992@gmail.com', u'fname': u'Rishikesh Agrawani'}
<type 'dict'> 

message Have a nice day.
contact 7353787704
email rishikesh0014051992@gmail.com
fname Rishikesh Agrawani

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()})

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM