'Attempting to combine JSON responses
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
