I have a JSON-File with some data in it. Now I try to extract some of the data, but I always get the error
Traceback (most recent call last):
File "C:\Users\Foo\PycharmProjects\youtube_stats\youtube_videos.py", line 29, in
title = vid["title"]
TypeError: string indices must be integers
Here's the code:
x= open("results/yt.json", mode="r")
vids = json.load(x)
for vid in vids[channel_id]["video_data"]:
vid_id = vid
title = vid["title"]
date = vid["publishedAt"]
likes = vid["likeCount"]
views = ["viewCount"]
comment_int =["commentCount"]
Here's the JSON-File:
{
"Foo": {
"channel_statistics": {
"viewCount": "20496906",
"subscriberCount": "220000",
"hiddenSubscriberCount": false,
"videoCount": "393"
},
"video_data": {
"video_id": {
"publishedAt": "2022-04-22T11:34:30Z",
"channelId": "Foo",
"title": "Foo",
"description": "Foo",
"thumbnails": {
"default": {
"url": "Foo",
"width": 120,
"height": 90
},
"medium": {
"url": "Foo",
"width": 320,
"height": 180
},
"high": {
"url": "Foo",
"width": 480,
"height": 360
}
},
"channelTitle": "Foo",
"categoryId": "24",
"liveBroadcastContent": "none",
"localized": {
"title": "Foo",
"description": "Foo"
},
"defaultAudioLanguage": "de",
"viewCount": "54991",
"likeCount": "886",
"favoriteCount": "0",
"commentCount": "1276",
"duration": "PT42M34S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"contentRating": {},
"projection": "rectangular"
},
I really can't find a solution, although it's probably very simple...
CodePudding user response:
As it's been mentioned in other comments, running for vid in vids[channel_id]["video_data"]:
will iterate through the dictionary keys. If you'd like to check the contents you can either use the key to access the values, or use dict.values()
to iterate through the dictionary values.
e.g. 1
for vid in vids[channel_id]["video_data"]:
title = vids[channel_id]["video_data"][vid]["title"]
or
e.g. 2
for vid in vids[channel_id]["video_data"].values():
title = vid["title"]
Check Python Docs for more info.