如何修复此错误:JSON解码错误:预期值:第1行第1列(字符0)

pdsfdshx  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(407)

我在尝试解码JSON时收到错误Expecting value: line 1 column 1 (char 0)
我将通过下面的代码进行API调用:

import requests
import json

base_url = "https://www.tropicos.org/Name/Search?name={name}&type={data_type}&apikey={api_key}&format={format_file}" #URL from Tropicos page

specie_name = "Quercus alba"
api_key = '###########'
data_type = "exact"
format_file = "json" #I also tried with the "xml" format
nameid_dict = {}

url = base_url
response = requests.get(url.format(name=specie_name, data_type=data_type, api_key=api_key, format_file=format_file))

到目前为止,代码工作正常,打印时响应状态为200,但错误出现在下一个代码中:

if response.status_code == 200:
    data = json.loads(response.content) #I also tried with the next code: data = response.json()
    nameid = data["Result"][0]["NameId"]

    # Store the NameID in the Dictionary
    nameid_dict[name] = nameid
else:
    print(f"Error al realizar la solicitud para {name}")

追溯:

JSONDecodeError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13580/1752249903.py in <module>
----> 1 data = json.loads(response.content)

C:\ProgramData\Anaconda3\lib\json\__init__.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    344             parse_int is None and parse_float is None and
    345             parse_constant is None and object_pairs_hook is None and not kw):
--> 346         return _default_decoder.decode(s)
    347     if cls is None:
    348         cls = JSONDecoder

C:\ProgramData\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

C:\ProgramData\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

救命啊

3pvhb19x

3pvhb19x1#

来自api的响应不是json格式,因此json模块无法解析它。
要了解发生的情况,请将行:

data = json.loads(response.content)

致:

print(response.text)
data = json.loads(response.content)

你将能够看到发生了什么。也因为它是简单的GET请求,尝试打开相同的网址在浏览器中,它可能会帮助您调试
可能是速率限制或访问权限错误,可能最好添加try/except以避免以后出现相同的错误

相关问题