當我嘗試讀取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