Sarabveer
Sarabveer

Reputation: 3

Cannot Loop Nested Json, get error (TypeError: list indices must be integers, not str)

So I have looked everywhere, and have not found a solution.

import urllib2
import json

shabad = raw_input('Shabad Number: ')
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}
igurbani_api =  urllib2.Request('https://lab.sarabveer.me/igurbani-api/?&mode=2&shabadNo=' + shabad + '&format=json', headers = hdr)
json_obj = urllib2.urlopen(igurbani_api)
data = json.load(json_obj)

for item in data['gurbani']['shabad']:
    print item['Gurmukhi']

When I run this I get error: TypeError: list indices must be integers, not str

Here is an example of what the actual JSON Looks like: EXAMPLE

I Basically need to Loop the JSON and display every Gurmukhi variable.

Upvotes: 0

Views: 85

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113988

data['gurbani'] is a list... as such

data['gurbani']["shabad"] is an error

try

for item in data['gurbani'][0]["shabad"]

or really probably

for translation in data['gurbani']:
    print translation["shabad"]["Gurmukhi"]

Upvotes: 1

qwertylpc
qwertylpc

Reputation: 2116

Try this:

for d in data['gurbani']:
    print d['shabad']['Gurmukhi']

This is because data['gurbani'] returns a list

Upvotes: 2

Related Questions