Question

[Solved] TypeError: string indices must be integers while parsing JSON, Python?

I’m trying to parse JSON, below is my code.

import requests
import json
yatoken = '123123sdfsdf'
listOfId = ['11111111111', '2222222222', '33333333333']
for site in listOfId:
   r = requests.get('http://api.ya-bot.net/projects/' + site  + '?token=' + yatoken)
parsed = json.loads(r.text)

for url in parsed['project']:
   #print url
   print str(url['name'])

And JSON:

{
"project":{
"id":"123123sdfsdfs",
"urls":[],
"name":"???",
"group":"??????",
"comments":"",
"sengines":[],
"wordstat_template":1,
"wordstat_regions":[]
}
} 

It gives this error

    print str(url['name'])
TypeError: string indices must be integers

How I can fix this problem?
Thx.

Enquirer: Anton

||

Solution #1:

The 'project' key refers to a dictionary. Looping over that dictionary gives you keys, each a string. You are not looping over the list of URLs. One of those keys will be 'name'

Your code is confusing otherwise. You appear to want to get each URL. To do that, you’d have to loop over the 'urls' key in that nested dictionary:

for url in parsed['project']['urls']:
    # each url value

In your sample response that list is empty however.

If you wanted to get the 'name' key from the nested dictionary, just print it without looping:

print parsed['project']['name']

Demo:

>>> import json
>>> parsed = json.loads('''
... {
... "project":{
... "id":"123123sdfsdfs",
... "urls":[],
... "name":"???",
... "group":"??????",
... "comments":"",
... "sengines":[],
... "wordstat_template":1,
... "wordstat_regions":[]
... }
... } 
... ''')
>>> parsed['project']
{u'group': u'u0413u0440u0443u043fu043fu0430', u'name': u'u0418u043cu044f', u'wordstat_regions': [], u'comments': u'', u'urls': [], u'sengines': [], u'id': u'123123sdfsdfs', u'wordstat_template': 1}
>>> parsed['project']['name']
u'u0418u043cu044f'
>>> print parsed['project']['name']
???
>>> print parsed['project']['urls']
[]
Respondent: Martijn Pieters

Solution #2:

for url in parsed['project'] returns a dict so you are actually iterating over the keys of the dict so "id"["name"] etc.. is going to error, you can use d = parsed['project'] to get the dict then access the dict by key to get whatever value you want.

d = parsed['project']
print(d["name"])
print(d["urls"])
...

Or iterate over the items to get key and value:

 for k, v in parsed['project'].items():
     print(k,v)

If you print what is returned you can see exactly what is happening:

In [17]: js = {
"project":{
"id":"123123sdfsdfs",
"urls":[],
"name":"???",
"group":"??????",
"comments":"",
"sengines":[],
"wordstat_template":1,
"wordstat_regions":[]
}
}

In [18]: js["project"] # dict
Out[18]: 
{'comments': '',
 'group': '??????',
 'id': '123123sdfsdfs',
 'name': '???',
 'sengines': [],
 'urls': [],
 'wordstat_regions': [],
 'wordstat_template': 1}

In [19]: for k in js["project"]: # iterating over the keys of the dict
   ....:     print(k)
   ....:     
sengines # k["name"] == error
id
urls
comments
name
wordstat_regions
wordstat_template
group

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy