python
data_error
ai_generated
true
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
80%Fix Rate
85%Confidence
0Evidence
2024-09-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
The server returned a non-JSON response (e.g., HTML error page) but the client expects JSON.
generic中文
服务器返回了非JSON响应(例如HTML错误页面),但客户端期望JSON。
Workarounds
-
95% success 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) -
90% success 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()
Dead Ends
Common approaches that don't work:
-
Using json.loads() directly on response.text without checking status
80% fail
The response may be an error page, not JSON, causing the same decode error.
-
Setting a custom decoder with strict=False
90% fail
The response is not JSON at all, so no decoder can parse it.