【发布时间】:2021-11-08 23:03:19
【问题描述】:
我有一个分页 API,我正在尝试浏览所有可用数据并将其保存到一个列表中。但是,我的 API 的本质是它是嵌套的,这里是它的外观示例。
"data": [{"type": "general-Type", "id": 1, "attributes": {"firstname": "Kevin", "lastname": "Wolf", "emailaddress": "kevinwolf@gmail.com"}}]
因此,当我将其保存到列表中时,数据的最后一部分(即“属性”)看起来像字典,导致以下错误:
sample_data.extend(sample_data['data'])
AttributeError: 'dict' object has no attribute 'extend'
我是新手,因此有关如何成功完成此请求的任何帮助都会有所帮助 提前谢谢你
如果有帮助,这是我的代码: 请求限制为 10,000,这就是我将限制设置为 10,000 增量的原因
sample_data = []
offset = 0
limit = 10000
while True:
print("----")
url = f"https://results.us.sampledata.com/api/reporting/v0.1.0/samples?offset={offset}&page[size]={limit}"
headers = {"Content-Type": "application/json", "Accept-Charset": "UTF-8", "x-apikey-token": "sampletoken"}
print("Requesting", url)
response = requests.get(url, data={"sample": "data"}, headers=headers)
sample_data = response.json()
if len(sample_data['data']) == 0:
# If not, exit the loop
break
# If we did find records, add them
# to our list and then move on to the next offset
sample_data.extend(sample_data['data'])
offset = offset + 10000
【问题讨论】:
-
sample_data = []和sample_data = response.json()。使用不同的名称。 -
这也不起作用,因为列表仍会将 json 的最后一部分视为 dict
-
dict 对象是
sample_data = response.json()。 -
尝试重命名:
sample_data_list = []和sample_data_list.extend(sample_data['data'])。 -
AttributeError: 'dict' object has no attribute 'extend'。这意味着您正在尝试对没有此方法的对象使用列表方法(扩展)。
标签: python json api python-requests pagination