简体   繁体   English

Python:查询字典到 JSON

[英]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.我试图通过使用encodeURIComponent()在查询字符串中将一些 JSON 发送到我的 django 应用程序,我的服务器端点接收数据就好了,因为我可以将其打印到 python 控制台。

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.我想将其转换为 JSON,这样我就可以用来获取一些信息,但我已经尝试使用json.loads和其他方法来操作数据,但没有运气。

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 ). QueryDict类是常规 Python 字典的子类,不同之处在于它处理同一个键的多个值(参见MultiValueDict实现)。

If you want to dump it to a string, just use json.dumps() :如果要将其转储为字符串,只需使用json.dumps()

json.dumps(my_query_dict) 

There is also a relevant dict() method:还有一个相关的dict()方法:

QueryDict.dict() QueryDict.dict()

Returns dict representation of QueryDict.返回 QueryDict 的 dict 表示。

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 .我正在使用Python 2.7.13Django 1.11.2 。您可以在字典中获取您的数据,以便您可以使用它们的相关访问这些数据

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 .但在这里我使用POST代替GET,因为我们将数据发布到服务器

So the above 1 line code is sufficient to get data as a dictionary in your case.因此,在您的情况下,上面的1 行代码足以将数据作为字典获取。

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:或使用 join 紧凑:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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