TypeError:当通过Python读取JSON时,字符串索引必须是整数

时间:2015-04-02 01:27:20

标签: python json

当我尝试读取JSON数据中的变量名时,我只是遇到了问题。 以下是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

3 个答案:

答案 0 :(得分:0)

  

我只想打印“轨道”

下“专辑”中的所有“类型”名称

然后你必须迭代items

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

答案 1 :(得分:0)

r['items'][0]['track']是一本字典。使用for对其进行迭代将列出键,当然是字符串。

答案 2 :(得分: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']