2015-04-02 42 views
0

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

的r [ '項'] [0] [ '軌道']'是一個** **字典。您正在迭代字典的鍵。我不清楚你爲什麼首先使用循環。如果你解釋你試圖達到的目標,我們可能會幫助你。 – 2015-04-02 01:30:53

+0

@FelixKling我只是想打印'track'下的'album'中的所有'type'名稱 – user3849475 2015-04-02 01:36:10

回答

0

I just want to print the all 'type' name which are in 'album' under the 'track'

然後你不得不遍歷items

for item in r['items']: 
    print(item['track']['album']['type']) 
+0

Thanks.I可以看到輸出。有沒有什麼方法可以使輸出像這樣?當我嘗試使用' – user3849475 2015-04-02 01:55:59

+0

使用.split()根據您的上述解決方案拆分類型失敗。 AttributeError:'list'對象沒有屬性'split'。我想獲得的理想輸出類型= ['artist','all','','best','album','this','is','occurrence'] – 2015-04-02 02:16:02

+0

'時,'[item''type'] ['item'] ['item']爲項目['items']] – user3849475 2015-04-02 12:29:08

0

r['items'][0]['track']是一本字典。使用for對它進行迭代將列出鍵,當然這些鍵是字符串。

+0

[']是什麼意思['items'] [0] ['track'] – user3849475 2015-04-02 12:29:37

+0

'r'是一個字典; 'r ['items']'是該字典中的數組; 'r ['items'] [0]'是該數組中的「第零個」(第一個)元素。 – Malvolio 2015-04-02 15:04:27

0

也許下面的代碼應該是正確的:

import json 
# test.json is your JSON data file. 
with file(r'test.json') as f: 
    jsonobj = json.load(f) 
    for i in range(len(jsonobj["items"])): 
     print jsonobj['items'][i]['track']['album']['type'] 
相關問題