You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中将字典转换为application/x-www-form-urlencoded编码数据

问题根因
  • 调用urlencode时传入doseq=True的作用就是将序列类型的参数拆分为多个同名参数传递,和你需要「将列表整体作为字符串编码」的需求逻辑冲突
  • urlencode默认使用quote_plus做编码,该方法会将空格编码为+,这是表单编码的常规实现,但不符合目标接口要求的%20空格编码规则
实现步骤
  1. 提前预处理字典数据:将列表类型的字段值转换为符合预期格式的字符串,这里直接用json.dumps()序列化列表即可,生成的字符串格式为带双引号、逗号后带空格的标准数组格式,和你要求的输出完全匹配,不需要手动拼接字符串处理转义
  2. 调用urlencode时指定编码方法为urllib.parse.quote,该方法会将空格编码为%20,满足接口要求
完整代码
import json
from urllib.parse import urlencode, quote

raw_data = {
   "name":"test name",
   "file_urls":[
      "/Users/tarequzzamankhan/Desktop/instagram.webp",
      "/Users/tarequzzamankhan/Desktop/instagram.webp"
   ],
   "file_type":"pdf",
   "user_name":"Tareq",
   "mobile":"018xxxxxxxxx",
   "address":"Dhaka",
   "email":"example@mail.com"
}

# 预处理非字符串类型的值
processed = {}
for key, value in raw_data.items():
    if isinstance(value, list):
        processed[key] = json.dumps(value)
    else:
        processed[key] = value

payload = urlencode(processed, quote_via=quote)
输出验证

执行上述代码生成的payload与预期结果完全一致:

name=test%20name&file_urls=%5B%22%2FUsers%2Ftarequzzamankhan%2FDesktop%2Finstagram.webp%22%2C%20%22%2FUsers%2Ftarequzzamankhan%2FDesktop%2Finstagram.webp%22%5D&file_type=pdf&user_name=Tareq&mobile=018xxxxxxxxx&address=Dhaka&email=example%40mail.com

注意:如果后续有其他非字符串类型的字段(比如字典、数字),也可以参照列表的处理逻辑,提前转成目标接口要求的字符串格式后再传入urlencode即可。

内容的提问来源于stack exchange,提问作者Tarequzzaman Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:06:25