用于 POST 请求 Python 的嵌套字典到 JSON [英] Nested Dictionaries to JSON for the POST request Python
问题描述
我无法以嵌套字典的形式转换有效负载数据,以将其作为使用 Python 请求模块的 POST 请求的数据传递.表单数据如下:
I am having trouble converting the payload data in the form of nested dictionaries to pass it as a data for the POST request using Python requests module. The form data is as below:
payload = {'request': {
'appkey': "936725A4-7D9A-11E5-81AC-86EC8D89CD5A"},
'formdata':{
'currency':'US',
'dataview':'store_default',
'distinct':'_distance, clientkey',
'geolocs':{
'geoloc':[{
'0':{
'address1':'',
'addressline':'19128, PA',
'city':'Philadelphia',
'country':'US',
'latitude':'40.0532987',
'longitude':'-75.23040379999998',
'postalcode':'19128',
'province':'',
'state':'PA'}}]
},
'google_autocomplete':'true',
'limit':'250',
'nobf':'1',
'searchradius':'15|25|50|100|250|350|450|550|650|750|850|950',
'true':'1',
'where':{'partner_reseller': {'eq':'1'}}}
}
r = requests.post(url,data=simplejson.dumps(payload),headers=header)
result = simplejson.loads(str(r.content))
有人可以帮助我了解结构并指出我所写的错误.我不断收到以下错误:
Can somebody please assist me with structure and can point out the mistake in what I have written. I keep getting the following error:
{'code': 1008,
'response': {'message': 'The submitted XML is not properly formed'}}
非常感谢您的帮助.谢谢.
I'll appreciate your help a lot. Thank you.
推荐答案
我遇到了类似的问题,很沮丧,但我解决了.Python 请求不适用于嵌套的 json,它们需要一层 json.它的处理方式类似于 form(application/x-www-form-urlencoded)
I had similar problem, frustrating but I solved it. Python requests do not work with nested json, they expect one layer json. It processes like form(application/x-www-form-urlencoded)
# Wrong
data = {'param1': {'a':[100, 200]},
'param2': 'value2',
'param3': False}
# You have to convert values into string:
data = {'param1': json.dumps({'a':[100, 200]}),
'param2': 'value2',
'param3': json.dumps(False)}
就你而言:
import json
params = {
'appkey': "936725A4-7D9A-11E5-81AC-86EC8D89CD5A"},
'formdata':{
'currency':'US',
'dataview':'store_default',
'distinct':'_distance, clientkey',
'geolocs':{
'geoloc':[{
'0':{
'address1':'',
'addressline':'19128, PA',
'city':'Philadelphia',
'country':'US',
'latitude':'40.0532987',
'longitude':'-75.23040379999998',
'postalcode':'19128',
'province':'',
'state':'PA'}}]
},
'google_autocomplete':'true',
'limit':'250',
'nobf':'1',
'searchradius':'15|25|50|100|250|350|450|550|650|750|850|950',
'true':'1',
'where':{'partner_reseller': {'eq':'1'}}}
}
payload = {'request': json.dumps(params) }
r = requests.post(url,data=payload) # important to keep payload as json!!!
result = r.text # or depends what the return is..
这篇关于用于 POST 请求 Python 的嵌套字典到 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!