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

从POSTMAN导出的Python代码报JSON格式错误请求失败求助

问题:Python请求报JSON格式错误,但Postman可正常请求

我用Postman导出的Python代码运行时抛出错误:

{"code":"E101","message":"JSON Error: Syntax error, malformed JSON"}

但在Postman中发起请求却能成功得到预期结果。以下是我的Python代码:

import requests

url = "APIURL"

payload={'data': '{
    "authenticate":{
        "apikey":"ABCSHF"
    },
    "services":[
        {
            "call":"history/API",
            "identifier":{
                "search":"desc"
            }
        }
    ]
}'}
files=[

]
headers = {

}

response = requests.request("POST", url, headers=headers, json=payload, files=files)

print(response.text)

解决方案

错误原因分析

  1. 多行字符串语法问题:Python中单行单引号字符串不支持直接换行,你给data赋值的多行JSON字符串会导致格式混乱,实际传递的内容已经不是合法的JSON。
  2. 双重JSON编码:requests的json=参数会自动将传入的字典序列化为JSON字符串,但你的payload里的data本身就是JSON字符串,这会导致服务器收到的是嵌套编码的JSON,自然解析失败。

修正方法(二选一)

方法1:直接使用Python字典(推荐)

把data对应的JSON结构写成Python字典,整个payload作为字典传给json=参数,requests会自动完成正确的JSON序列化:

import requests

url = "APIURL"

payload = {
    "data": {
        "authenticate": {
            "apikey": "ABCSHF"
        },
        "services": [
            {
                "call": "history/API",
                "identifier": {
                    "search": "desc"
                }
            }
        ]
    }
}
files = []
headers = {}

response = requests.request("POST", url, headers=headers, json=payload, files=files)

print(response.text)

方法2:使用JSON字符串并正确传递

如果必须用JSON字符串形式的data,需要用三引号包裹多行字符串,同时改用data=参数传递,并设置正确的请求头:

import requests

url = "APIURL"

payload = {
    "data": '''{
        "authenticate":{
            "apikey":"ABCSHF"
        },
        "services":[
            {
                "call":"history/API",
                "identifier":{
                    "search":"desc"
                }
            }
        ]
    }'''
}
files = []
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:54:24