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

FastAPI接收PHP数组Payload报错:无法识别输入为有效字典

解决FastAPI接收PHP数组Payload时的字典解析错误

错误原因

你收到的Payload是字符串包裹的JSON格式(错误信息里的input值为"{"test":"No","fields":"X"}"),而FastAPI期望的是原生JSON对象,因此dict类型校验失败。

解决方案

方案1:先接收字符串再解析为字典

修改接口参数类型为str,手动用json.loads解析成字典:

from fastapi import FastAPI
import json

app = FastAPI()

@app.post("/your-endpoint")
async def post(input_data: str):
    try:
        data_dict = json.loads(input_data)
        # 此处处理字典数据
        return {"status": "success", "data": data_dict}
    except json.JSONDecodeError:
        return {"status": "error", "msg": "无效的JSON格式字符串"}

方案2:修正PHP端的请求发送方式

让PHP发送标准JSON请求,而非字符串形式的JSON:

$payload = ["test" => "No", "fields" => "X"];
$ch = curl_init("http://your-fastapi-url/your-endpoint");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

调整后FastAPI直接用input_data: dict即可正常接收。

方案3:用Pydantic自定义解析规则

如果想保留dict或模型接收方式,可通过Pydantic校验器自动转换字符串:

from fastapi import FastAPI
from pydantic import BaseModel, field_validator
import json

app = FastAPI()

class RequestData(BaseModel):
    test: str
    fields: str

    @classmethod
    @field_validator('*', mode='before')
    def parse_json_str(cls, value):
        if isinstance(value, str):
            try:
                return json.loads(value)
            except json.JSONDecodeError:
                pass
        return value

@app.post("/your-endpoint")
async def post(input_data: RequestData):
    return {"received_data": input_data.dict()}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 23:15:01