2015-04-02 43 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'] 
相关问题