当前位置:   article > 正文

json格式化response报警json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.decoder.jsondecodeerror: expecting value: line 1 column 1 (char 0)

遇到问题

requests请求相应结果json()化时,提示 "JSONDecodeError: Expecting value: line 1 column 1 (char 0)"

  1. import json
  2. import requests
  3. resp = requests.get(url).json()
  1. def raw_decode(self, s, idx=0):
  2. """Decode a JSON document from ``s`` (a ``str`` beginning with
  3. a JSON document) and return a 2-tuple of the Python
  4. representation and the index in ``s`` where the document ended.
  5. This can be used to decode a JSON document from a string that may
  6. have extraneous data at the end.
  7. """
  8. try:
  9. obj, end = self.scan_once(s, idx)
  10. except StopIteration as err:
  11. > raise JSONDecodeError("Expecting value", s, err.value) from None
  12. E json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
  13. ../../../../../.pyenv/versions/3.9.4/lib/python3.9/json/decoder.py:355: JSONDecodeError

解决方案:

这个报错的原因有很多,我的原因是域名或者uri写错了。导致请求响应了404, 这个响应消息体无法被json格式化,从而报错。更多原因可以参考:JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

排查过程

直接执行上面的脚本,发现报出上述报警,可以看出是json格式出问题了,所以打算先去除json格式化这个步骤,先打印出response

  1. import json
  2. import requests
  3. resp = requests.get(url).json()

去除json()

  1. import json
  2. import requests
  3. resp = requests.get(url)
  4. 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格式化,从而报错。

转载:https://blog.csdn.net/qq_41767116/article/details/119814928

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/484930
推荐阅读
相关标签
  

闽ICP备14008679号