2

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.

1
  • 1
    Just so you know, you can replace parsed = json.loads(r.text) with parsed = r.json(), requests has that built in. Commented Aug 26, 2015 at 14:37

2 Answers 2

2

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'\u0413\u0440\u0443\u043f\u043f\u0430', u'name': u'\u0418\u043c\u044f', u'wordstat_regions': [], u'comments': u'', u'urls': [], u'sengines': [], u'id': u'123123sdfsdfs', u'wordstat_template': 1}
>>> parsed['project']['name']
u'\u0418\u043c\u044f'
>>> print parsed['project']['name']
Имя
>>> print parsed['project']['urls']
[]
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I have another question: How can i get 'name' of this listOfId = ['11111111111', '2222222222', '33333333333'] ? Without loop?
I have no idea what you are asking there.
sorry. we have 3 'id': '11111111111', '2222222222', '33333333333'. I want to get 3 'names' and use this: for site in listOfId. But I receive 1 result
But there is no list of names. What did you want to match this agains, your sample response is just one project object. Again, you are not being clear as to how the values in listOfId should map to the data returned from the API.
1. i do request: api.ya-bot.net/projects' + site + '?token=' + yatoken, where site is one of listOfId.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.