使用嵌套字典对URL进行编码 [英] Encode URL with nested dictionaries
问题描述
我使用的API在请求的正文中不接受JSON.它使用x-www-form-urlencoded
.
I am using an API that doesn't accept JSON in the requests' bodies. It uses x-www-form-urlencoded
.
因此,如果我必须发送此dict
:
Thus, if I have to send this dict
:
{
'a': 1,
'b': 2,
'c': {
'k': 3,
'v': 4,
'l': {
'p': 5,
'q': 6,
},
},
}
必须这样编码:
a=1
b=2
c[k]=3
c[v]=4
c[l][p]=5
c[l][q]=6
但是,urllib.parse.urlencode
不会以这种方式解析dict
.相反,它将直接对c
内容进行编码并将其放入(c5)中.
However, urllib.parse.urlencode
won't parse the dict
this way. Instead it's going to encode c
content literally and put within it (c={encodeddict}
).
我尝试自己实现一些编码器,但是我无法处理多个嵌套的dicts
.我只设法编码1级dicts
(如c[k]=3
),但没有递归编码到最后一级(例如,c[l][p]=5
).
I tried to implement some encoder like this by myself, but I couldn't get to deal with multiple nested dicts
. I only managed to encode 1-level dicts
(like c[k]=3
), but not recursively to the last level (c[l][p]=5
, for example).
在Python 3中实现这种编码的最佳方法是什么?
What is the best way to achieve this kind of encoding in Python 3?
推荐答案
使用递归:
将您的字典传递到dict_to_urlencoded(),它将根据您的描述返回编码格式的字符串. (未排序)
pass your dict to dict_to_urlencoded(), and it'll return encoded format string based on your description. (unsorted)
def dict_to_urlencoded(d):
return kv_translation(d, "", "")
def kv_translation(d, line, final_str):
for key in d:
key_str = key if not line else "[{}]".format(key)
if type(d[key]) is not dict:
final_str = "{}{}{}={}\n".format(final_str, line, key_str, d[key])
else:
final_str = kv_translation(d[key], line + key_str, final_str)
return final_str
这篇关于使用嵌套字典对URL进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!