Python请求.json()显示错误


import requests
r = requests.get("http://link-short.rf.gd/codes/hello/package.json")
r.json()

代码显示

File "c:file.py", line 3, in <module>
r.json()
File "C:Users88019AppDataLocalProgramsPythonPython39libsite-packagesrequestsmodels.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "C:Users88019AppDataLocalProgramsPythonPython39libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:Users88019AppDataLocalProgramsPythonPython39libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:Users88019AppDataLocalProgramsPythonPython39libjsondecoder.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)

问题出在哪里?我该如何解决?

问题在于JSON不是无效的。确切地说,问题不在于链接,而在于file_2.txt文件。所以你有两个解决方案:检查file_2.text文件,得到一个正确的JSON文件,因为这个文件不是。或者,如果你真的无法获得JSON文件,你可以通过插入一个应用于你的文件的请求来修改你的代码,因为当你运行r(因此是一个请求(时,它会根据头http对响应的编码进行假设。要更改编码,可以将r.json((替换为r.text((,如下所示:

import requests
r = requests.get ("http://link-short.rf.gd/codes/hello/file_2.txt")
r.text()

更新

我注意到你后来更改了问题中的链接。试试这些

import json
import requests
r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = r.json()

或者这个,因为它转换了一个字符串来访问您的JSON

import json
import requests
r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = json.loads(r.text)

http://link-short.rf.gd/codes/hello/file_2.txt不提供json。

因此,您可以提供一个指向json文件的链接

如果r不是json文件,则不能调用r.json((。由于您的URL指向一些file_2.txt,因此它不是json((格式,因此r.json(((对您没有帮助。

考虑使用r.text((代替

相关内容

最新更新