How can I loop over entries in JSON?

Question:

I want to loop over the content of a JSON file and print it to the console.

I think I did mix up something with lists.

This is what I tried to get all the team_name elements

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i

And this is my JSON (simplified:)

{
    "team": [
        {
            "team_icon_url": "http://www.openligadb.de/images/teamicons/Hamburger_SV.gif",
            "team_id": "100",
            "team_name": "Hamburger SV"
        },
        {
            "team_icon_url": "http://www.openligadb.de/images/teamicons/FC_Schalke_04.gif",
            "team_id": "9",
            "team_name": "FC Schalke 04"
        }
    ]
}

(Full JSON output to be found here: Link)

And of course I get an error, that I should use integer input in [], not string, but I don’t get how I could do that.

for i in json_obj['team']:
TypeError: string indices must be integers, not str

Here is the response:

http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1
<addinfourl at 139755086292608 whose fp = <socket._fileobject object at 0x7f1b446d33d0>>

What did I get wrong?

Asked By: mcbetz

||

Answers:

Try this :

import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
    print 'No Data!'
else:
    for rows in json_object['team']:
        print 'Team ID:' + rows['team_id']
        print 'Team Name:' + rows['team_name']
        print 'Team URL:' + rows['team_icon_url']
Answered By: Prem Minister

To decode json, you have to pass the json string. Currently you’re trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

Answered By: Karoly Horvath

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']
Answered By: mcbetz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.