Home > Mobile >  Attempting to combine JSON responses
Attempting to combine JSON responses

Time:04-09

I am attempting to call multiple pages of an API and combine their responses.

# function to get return data from all pages
def getplayerdata(pages, url):
    print("Fetching "   str(pages)   " pages.")
    # create blank playerdata object
    playerdata = {"listings": []}
    for x in range(pages):
        currentPageNum = x 1
        currentPageURL = url   str(currentPageNum)
        print("Getting data from: "   currentPageURL)
        dataFetch = getpagedata(currentPageURL)
        newPlayerData = dataFetch['listings']
        playerdata["listings"].append(newPlayerData)
    return playerdata

It seems like I am 95% of the way there. The issue is that my JSON output isn't formatted perfectly. Right now the output is showing as:

"listings": [
    [
        {data from page one}
    ]
    [
        {data from page two}
    ]
]

I am looking for:

"listings": [
    {data from page one},
    {data from page two}
]

Any ideas? Am I doing something completely wrong?

CodePudding user response:

Change

playerdata["listings"].append(newPlayerData)

to

playerdata["listings"].extend(newPlayerData)

You want to add the elements of newPlayerData to the playerdata["listings"] list, not the newPlayerData list itself.

  • Related