Reputation: 27
So I'm trying to parse the following response (JSON Response), here's a sample:
{
"kind": "youtube#searchListResponse",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/fywkWrox-IkW0v2IWY27RMiWvvA\"",
"nextPageToken": "CBQQAA",
"regionCode": "IQ",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 20
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/j0uEstXCXOhrDqDegEBmEeHqsBM\"",
"id": {
"kind": "youtube#video",
"videoId": "YQHsXMglC9A"
},
"snippet": {
"publishedAt": "2015-10-23T06:54:18.000Z",
"channelId": "UComP_epzeKzvBX156r6pm1Q",
"title": "Adele - Hello",
"description": "'Hello' is taken from the new album, 25, out November 20. http://adele.com Available now from iTunes http://smarturl.it/itunes25 Available now from Amazon ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/YQHsXMglC9A/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/YQHsXMglC9A/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/YQHsXMglC9A/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "AdeleVEVO",
"liveBroadcastContent": "none"
}
}
And this is my parsing function:
def parse(self):
items = self['items']
i = 0
for item in items:
Data = {str(i): {
"id": item['id']['videoId'],
"title": item['snippet']['title'],
"description": item['snippet']['description'],
"thumbnail": item['snippet']['thumbnails']['medium']['url'],
"publishedAt": item['snippet']['publishedAt'],
"FullURL": "https://www.youtube.com/watch?v=" + item['id']['videoId']
}}
i = i +1
return Data
The main problem is that the dictionary is only inserting the last bit of the response, for example, I'm fetching 10 results, and it's only returning the last response. What's the problem?
Upvotes: 0
Views: 25
Reputation: 13175
Just take the definition of Data
out of the for
loop, initialise it as an empty dictionary and then add key/value pairs to it on each iteration. Currently, you keep redefining the entire dictionary on each loop, containing a single entry. You then end up return
ing the final version.
def parse(self):
items = self['items']
Data = {} # Initialise it here
for i, item in enumerate(items): # Now you don't need to increment i
# Insert your key/value pair
Data[str(i)] = {
"id": item['id']['videoId'],
"title": item['snippet']['title'],
"description": item['snippet']['description'],
"thumbnail": item['snippet']['thumbnails']['medium']['url'],
"publishedAt": item['snippet']['publishedAt'],
"FullURL": "https://www.youtube.com/watch?v=" + item['id']['videoId']
}
return Data
Upvotes: 1