python data_error ai_generated true

JSON 解码错误:期望值:第 1 行第 1 列(字符 0)。

json.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

ID: python/starlette-request-body-parsing

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-04-14首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

请求体为空或不是有效的 JSON,但尝试用 request.json() 解析。

English

Request body is empty or not valid JSON when trying to parse with request.json().

generic

解决方案

  1. 90% 成功率
    Check content-type first: if request.headers.get('content-type') == 'application/json':
        data = await request.json()
    else:
        return JSONResponse(status_code=415)
  2. 85% 成功率
    Use a middleware to parse JSON and handle errors gracefully.

无效尝试

常见但无效的做法:

  1. 50% 失败

    Works but masks the root cause; better to validate request content type.

  2. 60% 失败

    body() returns bytes; need to decode and json.loads.