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
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().
解决方案
-
90% 成功率
Check content-type first: if request.headers.get('content-type') == 'application/json': data = await request.json() else: return JSONResponse(status_code=415) -
85% 成功率
Use a middleware to parse JSON and handle errors gracefully.
无效尝试
常见但无效的做法:
-
50% 失败
Works but masks the root cause; better to validate request content type.
-
60% 失败
body() returns bytes; need to decode and json.loads.