python data_error ai_generated true

requests.exceptions.JSONDecodeError: 期望值:第1行第1列(字符0),解析来自'https://api.example.com/v1/data'的响应时出错

requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) while parsing response from 'https://api.example.com/v1/data'

ID: python/requests-jsondecodeerror-invalid-response

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

版本兼容性

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

根因分析

服务器返回了非JSON响应(例如HTML错误页面),但客户端期望JSON。

English

The server returned a non-JSON response (e.g., HTML error page) but the client expects JSON.

generic

解决方案

  1. 95% 成功率 Check the response status code and content type before parsing JSON
    response = requests.get('https://api.example.com/v1/data')
    if response.status_code == 200 and 'application/json' in response.headers.get('Content-Type', ''):
        data = response.json()
    else:
        print('Unexpected response:', response.text)
  2. 90% 成功率 Use response.raise_for_status() to catch HTTP errors before parsing
    response = requests.get('https://api.example.com/v1/data')
    response.raise_for_status()
    data = response.json()

无效尝试

常见但无效的做法:

  1. Using json.loads() directly on response.text without checking status 80% 失败

    The response may be an error page, not JSON, causing the same decode error.

  2. Setting a custom decoder with strict=False 90% 失败

    The response is not JSON at all, so no decoder can parse it.