嵌套 Json 的分页

pagination for nested Json

我有一个分页 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

正如@8349697 已经说过的,您的问题是您使用相同的名称sample_data 来保留两个不同的结构。

首先你创建列表 sample_data = [] 但后来你用字典覆盖它 sample_data = response.json() 但接下来你想使用原始列表 sample_data 从字典添加值 sample_data

您应该使用不同的名称,例如

page_data = response.json()

if not page_data['data']: # if len(page_data['data']) == 0:
    break

sample_data.extend(page_data['data'])

具有其他更改的最少代码 - 但我无法使用您的 url.

对其进行测试
import requests

sample_data = []

headers = {
    "Content-Type": "application/json",
    "Accept-Charset": "UTF-8",
    "x-apikey-token": "sampletoken"
}

data = {
    "sample": "data"
}

params = {
    "offset": 0,
    "page[size]": 10000,
}

url = "https://results.us.sampledata.com/api/reporting/v0.1.0/samples"

while True:
    print("----")
    
    #url = f"https://results.us.sampledata.com/api/reporting/v0.1.0/samples?offset={offset}&page[size]={limit}"
    #print("Requesting", url)
    
    print('Offset:', params['offset'])

    response = requests.get(url, params=params, data=data, headers=headers)
    page_data = response.json()

    if (not 'data' in page_data) or (not page_data['data']): 
        break

    sample_data.extend(page_data['data'])

    params['offset'] += 10000