使用for循环访问嵌套的JSON元素

时间:2019-01-19 22:02:15

标签: python json

我正在尝试遍历作为响应收到的嵌套JSON。

这是响应:

{
  "nextPageToken": "CAUQAA",
  "items": [
    {
      "contentDetails": {
        "videoPublishedAt": "2009-09-23T11:07:45.000Z",
        "videoId": "1zagQpB_c0M"
      },
      "kind": "youtube#playlistItem",
      "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk\/NW6JAIYqE0f-uUkRnhYDTMiJ1nw\"",
      "id": "UEwwUDR2SVRPd1k0VGFyNXhxeUhCbllPd0Z4TDRpc1d0VS41NkI0NEY2RDEwNTU3Q0M2"
    },
    {
      "contentDetails": {
        "videoPublishedAt": "2007-11-26T01:23:19.000Z",
        "videoId": "GoCOg8ZzUfg"
      },
      "kind": "youtube#playlistItem",
      "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk\/ogX8pxR3cwm0xA6DQhc7j_tuuHw\"",
      "id": "UEwwUDR2SVRPd1k0VGFyNXhxeUhCbllPd0Z4TDRpc1d0VS4yODlGNEE0NkRGMEEzMEQy"
    },
    {
      "contentDetails": {
        "videoPublishedAt": "2008-07-08T17:39:12.000Z",
        "videoId": "6Y-DjurrO08"
      },
      "kind": "youtube#playlistItem",
      "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk\/NNzmeRr-3TfKHRfxmkOArbnNSII\"",
      "id": "UEwwUDR2SVRPd1k0VGFyNXhxeUhCbllPd0Z4TDRpc1d0VS45ODRDNTg0QjA4NkFBNkQy"
    },
    {
      "contentDetails": {
        "videoPublishedAt": "2009-07-05T13:31:44.000Z",
        "videoId": "_EQYndFqMS0"
      },
      "kind": "youtube#playlistItem",
      "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk\/90b0La1GsJV5pfaAYn0Kd7OJpWA\"",
      "id": "UEwwUDR2SVRPd1k0VGFyNXhxeUhCbllPd0Z4TDRpc1d0VS4xM0YyM0RDNDE4REQ1NDA0"
    }
  ],
  "kind": "youtube#playlistItemListResponse",
  "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk\/TwSA9klp7PJcoEjYfML5mdmYI-0\"",
  "pageInfo": {
    "resultsPerPage": 5,
    "totalResults": 55
  }
}

我尝试(并成功)访问了我的词典的外部层次。另外,我可以对需要的内容进行硬编码,见下文。

对需要的数据进行硬编码访问

    print data['items'][0]['contentDetails']['videoId']:

这就是我试图遍历响应的方式:

    for i in data['items'][0]['contentDetails']['videoId']:
        print i

上面的for循环将循环我'videoID'具有的字符数。

如何使用for循环访问每个“ videoID” json元素?

2 个答案:

答案 0 :(得分:1)

您需要遍历项目:

for item in data['items']:
    print item['contentDetails']['videoId']

答案 1 :(得分:0)

我是afk,所以我不能给你代码,但您可能想看看json包,它简化了数据结构的处理。至少在我看来尤其如此... Sorrz评分过低,无法添加答案而不是答案