json格式化response報警json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
阿新 • • 發佈:2021-08-19
遇到問題
將requests請求相應結果json()化時,提示 "JSONDecodeError: Expecting value: line 1 column 1(char 0)"
import json import requests resp = requests.get(url).json()
def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.""" try: obj, end = self.scan_once(s, idx) except StopIteration as err: > raise JSONDecodeError("Expecting value", s, err.value) from None E json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ../../../../../.pyenv/versions/3.9.4/lib/python3.9/json/decoder.py:355: JSONDecodeError
解決方案:
這個報錯的原因有很多,我的原因是域名或者uri寫錯了。導致請求響應了404, 這個響應訊息體無法被json格式化,從而報錯。更多原因可以參考:JSONDecodeError:期望值:第 1 行第 1 列(字元 0)
排查過程
直接執行上面的指令碼,發現報出上述報警,可以看出是json格式出問題了,所以打算先去除json格式化這個步驟,先打印出response
import json import requests resp = requests.get(url).json()
去除json()
import json import requests resp= requests.get(url)
print("resp: %s" % resp)
執行結果如下
resp: <Response [404]>
發現響應了404, 說明可能是uri寫錯了, 排查uri之後,發現確實是寫錯了,改正uri之後,再次執行
執行結果如下
resp: <Response [200]>
響應正常了,再加上json()格式化語句,不報上述提示 "JSONDecodeError: Expecting value: line 1 column 1(char 0)"問題了。說明是響應404導致響應體不能被json格式化,從而報錯。