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

如何用Python Requests将POST请求体正确格式化为JSON?

问题分析与解决方案

你的请求失败核心有两个问题:

  1. JSON语法错误:"columns"[]不是合法的JSON键名,且重复定义同一键在JSON中无效(会被忽略或触发解析错误)。
  2. 请求格式不匹配:原请求是application/x-www-form-urlencoded(URL编码表单),若后端仅支持该格式,强行转JSON发送无法被正确解析。

以下是两种针对性解决方法:

方法一:直接发送URL编码表单数据(推荐,匹配原请求格式)

无需手动转JSON,用requests.post的data参数传入字典,requests会自动编码为和原请求一致的URL格式:

import requests

target_url = "你的目标接口URL"
form_data = {
    "nonce": "b3272d453ca8734f8df1c78ce201f00c",
    "from": "01/12/22",
    "to": "31/12/22",
    "columns": [
        "Transaction.DateTimeConverted",
        "Terminal.Id"
    ]
}

# requests自动将columns数组转为columns[]=xxx&columns[]=yyy的URL编码格式
response = requests.post(target_url, data=form_data)
print(response.text)

方法二:若后端支持JSON格式(需提前确认)

如果后端明确接受application/json格式,修正JSON数组表示为合法语法"columns": ["值1", "值2"],再用json参数发送:

import requests

target_url = "你的目标接口URL"
json_data = {
    "nonce": "b3272d453ca8734f8df1c78ce201f00c",
    "from": "01/12/22",
    "to": "31/12/22",
    "columns": [
        "Transaction.DateTimeConverted",
        "Terminal.Id"
    ]
}

# requests自动设置Content-Type为application/json并序列化数据
response = requests.post(target_url, json=json_data)
print(response.text)

关键提示

优先使用方法一,因为原请求是URL编码表单格式,后端大概率仅处理该类型请求。若必须用JSON,需先确认后端是否支持该格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:40:16