Watch at Ease看見世界,讀懂生活。

科技 · 實用指南

requests 出現 JSONDecodeError char 0?解析前先證明 response bytes

保存最終 URL、status、Content-Type、raw byte 長度與安全 prefix,再區分合法空 response、HTML/text、已消耗 stream 與 JSON。

zh-TW diagram of the HTTP response evidence chain before JSON parsing
原創插畫:解析前保存完整 response 證據鏈。 Watch at Ease

“Expecting value: line 1 column 1 (char 0)” 只表示 parser 在起點找不到 JSON value,不證明 quote、library 或 server 一定故障。

重試前固定同一 response 的 request、redirect、status、media type、byte length 與去識別 prefix,讓證據指向真正 boundary。

重試前凍結一次失敗交換

記錄同一失敗 call 的 method、去識別 target、status_code、final URL 與 redirect history;可用時保存時間與 correlation ID。

不要記錄 credential、cookie、Authorization 或無界 body;只保留選定 header 與短去識別 prefix。

選擇 parser 前先量測 bytes

把 response.content 一次讀入 bounded variable 並記錄長度;零 bytes 代表不存在 JSON document。

若使用 stream=True,要證明 consumption owner;iter_content、raw.read 或 middleware 可能已推進到 EOF。

一起解讀 status、redirect 與 Content-Type

Requests 說明 204 或 invalid body 會讓 json() 丟出錯誤;204 可能是合法 outcome,應依 endpoint contract 回傳「無物件」。

檢查 final URL 和 redirects;login、rate-limit、404 HTML 或 502 gateway 常以「<」開頭並在 char 0 失敗。

分開 HTTP failure 與 representation failure

是否先 raise_for_status 取決於 API contract;有些 error status 回傳 JSON,有些回傳 HTML。

status 異常先修 auth、endpoint、redirect、proxy 或 upstream;status 正常但 representation 不符則保留 sample。

只 parse 一次並證明 exit condition

只有 contract 允許 JSON 且 bytes 非空時才呼叫 response.json() 或 json.loads(body)。

以同一 runtime 與 network path 重跑:expected status、compatible type、non-zero bytes、single parse 與 schema validation 全通過才結案。

zh-TW decision tree for empty, non-JSON and JSON response bodies
原創插畫:依空、非 JSON 與 JSON bytes 分支。 Watch at Ease