dld
dld

Reputation: 43

Accessing nested JSON elements with for loop

I'm trying to iterate through a nested JSON that I received as a response.

This is the response:

{
  "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
  }
}

I have tried (and succeeded) in accessing outer levels of my dict. Also, I can hardcode what I need, see below.

Hardcoding access to data I need:

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

This is how I'm trying to loop over the response:

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

The for loop above loops I times where I is num of characters 'videoID' has.

How can I access each individual 'videoID' json element with a for loop?

Upvotes: 0

Views: 94

Answers (2)

Prometheus
Prometheus

Reputation: 92

I`m afk so I can't give u the code but you may want to have a look at the json package, which simplifies data structure handling. Especially searching at least in my opinion... Sorrz too low rated to add a xomment instead of an answer

Upvotes: 0

chinloyal
chinloyal

Reputation: 1141

You need to loop through items:

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

Upvotes: 1

Related Questions