cturner0098
cturner0098

Reputation: 17

How do I iterate over JSON children in python?

I'm trying to iterate over a JSON response from google sheets API. My goal is to get the values of each title ('Chapter 1', 'Chapter 2', etc...), but I cannot further iterate past the first child of the object.

I'm trying to parse through this response.

This is what I currently have:

request = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID, ranges=ranges, includeGridData=include_grid_data)
    response = request.execute()
    print(response)
    for x in response['sheets']:
        print(response['properties']['title'])

And it returns only 少女終末旅行 Volume 1 Vocab(as to be expected, as it iterator isn't used).

If I add an index after 'title', it returns the character at the index of that iterator. If I put it all into response['sheets']['properties']['title'] , it throws TypeError: list indices must be integers or slices, not str

Upvotes: 0

Views: 1160

Answers (3)

Venkata Muttineni
Venkata Muttineni

Reputation: 86

You could write print(response[x]) not the response[properties][title]

Or

You can write x["name].

Please let me know if you have any questions. I would be very happy to help you on this.

Upvotes: 0

Deepak Dixit
Deepak Dixit

Reputation: 1620

You should try something like this:-

# Codes ...
print(response)
for sheet in response['sheets']:
  print(sheet['properties']['title'])

Once you are using for x in y then you have to use x to get further values.

Upvotes: 0

Rusty
Rusty

Reputation: 1123

In your for loop, you should be working on the x variable, not on response

for x in response['sheets']:
    print(x['properties']['title']

Upvotes: 1

Related Questions