我收到以下错误消息:
...文件“ c:\ users \ dockerhost \ appdata \ local \ programs \ python \ python37 \ Lib \ json \ decoder.py”,行355,在raw_decode中 从None提高JSONDecodeError(“期望值”,s,err.value) json.decoder.JSONDecodeError:期望值:第1行第1列(字符0)
我正在尝试使用请求来获取响应头。我已经尝试解决jsondecodeerror进行了大量研究。但是,我没有找到解决方案。
import requests
request.get('https://www.google.com/').json()
Error message.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Host\.virtualenvs\projects08-8iyGSYl4\lib\site-packages\requests\models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "c:\users\host\appdata\local\programs\python\python37\Lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "c:\users\host\appdata\local\programs\python\python37\Lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\users\host\appdata\local\programs\python\python37\Lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
答案 0 :(得分:1)
JSON解码器在第一行的第一个字符处期望有一个值,只是意味着它找不到要解析的内容。也就是说,您的响应对象的内容为空。
您应该使用以下命令检查服务器响应的内容:
print(request.get(your_url).content)
确保它不为空并且实际上是有效的JSON。
如果确实为空,则通常意味着您没有向服务器发送期望的消息,并且应该修复与请求一起发送的标头/ cookies /身份验证/ API密钥/参数。
答案 1 :(得分:1)
从文档中
ResponseObj.json()
返回结果的JSON对象(如果结果以JSON格式编写,否则返回错误)
由于结果不是JSON格式,因此您会收到错误消息。
如果结果是有效的JSON,
>>> requests.get('https://jsonplaceholder.typicode.com/todos/1').json()
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
该函数确实返回JSON。
答案 2 :(得分:0)
使用request.get('https://www.google.com/').json()
时,您会盲目地将HTTP响应内容转换为JSON。根据URL,响应可能是JSON,也可能不是。在这里,google页面是HTML而不是JSON。
从documentation可以清楚地看到,如果内容不是JSON,json()
调用将引发错误。
但是,您提到了响应头。可以使用request.get('https://www.google.com/').headers
访问响应头,import json
import requests
header_json = json.dumps(dict(requests.get('https://www.google.com/').headers))
pprint(header_json)
是头的字典表示。如果您希望将其设为json,则只需加载即可
{
"Alt-Svc": "quic=\":443\"; ma=2592000; v=\"46,43,39\"",
"Cache-Control": "private, max-age=0",
"Content-Encoding": "gzip",
"Content-Type": "text/html; charset=ISO-8859-1",
"Date": "Wed, 28 Aug 2019 06:20:28 GMT",
"Expires": "-1",
"P3P": "CP=\"This is not a P3P policy! See g.co/p3phelp for more info.\"",
"Server": "gws",
"Set-Cookie": "######################removed purposefully##########################",
"Transfer-Encoding": "chunked",
"X-Frame-Options": "SAMEORIGIN",
"X-XSS-Protection": "0"
}
这将给您类似
的结果i := 0
var i = 0
这是您想要实现的目标吗?
答案 3 :(得分:0)
要避免此错误,请首先检查您是否得到了一个与 200 不同的status_code
。可能服务器正在返回一个 <Response [204]>
my_response = requests.get(MY_URL)
if my_response.status_code == 200:
my_response.json()
else:
...