【问题标题】:JsonDecodeError while fetching response from API从 API 获取响应时出现 JsonDecodeError
【发布时间】:2020-05-10 16:51:50
【问题描述】:

所以我试图从一个 api 获得一个简单的响应,当我尝试从 api 拉一个响应时,我得到一个错误: JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

import requests
import json
current = "https://covidtracking.com/api/v1/states/current"
response = requests.get(current)
print(response.status_code)
gg = json.dumps(response.json(), indent = 4)

回溯如下:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-27-c5319b3765a1> in <module>
----> 1 gg = json.dumps(response.json(), indent = 4)

~\anaconda3\lib\site-packages\requests\models.py in json(self, **kwargs)
    895                     # used.
    896                     pass
--> 897         return complexjson.loads(self.text, **kwargs)
    898 
    899     @property

~\anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

~\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):

~\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)
​

我到底做错了什么?我也很感激有关使代码更好或更高效的提示,我仍在学习如何编写 Python 代码。

谢谢!

【问题讨论】:

标签: python json api


【解决方案1】:

您正在尝试使用 API 的 HTML 版本。相反,请将您的代码指向使用以下 URL。

import requests
import json
current = "https://covidtracking.com/api/v1/states/current.json"
response = requests.get(current)
print(response.status_code)
#get the data from the API response as JSON
covid_data = response.json()
#Since we have the data by state, loop through each state
for data in covid_data:
    #read the individual attributes from the data for each state and print / process as required.
    print(f"{data['state']}-{data['positive']}")

请参阅此URL,其中详细介绍了返回 JSON 和返回 CSV 的 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2021-12-26
    • 2019-05-06
    • 1970-01-01
    • 2017-01-17
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多