当我尝试读取JSON数据中的变量名称时,我只是遇到问题。 以下是示例Json数据集。TypeError:当通过Python读取JSON时,字符串索引必须是整数
{
"items" : [ {
"added_at" : "2015-01-15T12:39:22Z",
"added_by" : {
"id" : "jmpe",
"type" : "user",
"uri" : "youtube:user:jmperezperez"
},
"is_local" : false,
"track" : {
"album" : {
"album_type" : "album",
"id" : "2pADiw4ko",
"name" : "All The Best",
"type" : "artist all the best"
},
"disc_number" : 1,
"duration_ms" : 376000,
"explicit" : false,
"id" : "4jZ",
"name" : "Api",
"popularity" : 8,
"track_number" : 10,
"type" : "track",
"uri" : "youtube:track:4jZ"
}
},{
"added_at" : "2013-05-30T15:49:25Z",
"added_by" : {
"id" : "jmpe",
"type" : "user",
"uri" : "youtube:user:jmperezperez"
},
"is_local" : false,
"track" : {
"album" : {
"album_type" : "album",
"id" : "2pADiw4ko",
"name" : "This Is Happening",
"type" : "album this is happening"
},
"disc_number" : 1,
"duration_ms" : 376000,
"explicit" : false,
"id" : "abc",
"name" : "Api",
"popularity" : 8,
"track_number" : 10,
"type" : "track",
"uri" : "youtube:track:abc"
}
}
],
"limit" : 100,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 5
}
我想打印轨道下专辑中的所有类型。
for play_track in r['items'][0]['track']:
type =play_track['album'][0]['type']
print(type)
有一个错误消息。但我不知道如何解决它。谢谢。
Traceback (most recent call last):
File "C:\Users\Desktop\code\track2.py", line 15, in <module>
type =play_track['album'][0]['type']
TypeError: string indices must be integers
的r [ '项'] [0] [ '轨道']'是一个** **字典。您正在迭代字典的键。我不清楚你为什么首先使用循环。如果你解释你试图达到的目标,我们可能会帮助你。 – 2015-04-02 01:30:53
@FelixKling我只是想打印'track'下的'album'中的所有'type'名称 – user3849475 2015-04-02 01:36:10