Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - How can I loop over entries in JSON?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...