You Awesum
You Awesum

Reputation: 114

TypeError: string indices must be integers error from jSON and Flask

I'm a newbie at python programming. It taking me long hours but still I cant debug it. What i'm trying to do is that i'm accessing a JSON object but unfortunately it returns an error to me.

This is my sample JSON from RESTFUL API:

{"matchday": 23, "standing": [{"teamId": 65, "goalsAgainst": 17, "points": 62, "playedGames": 23, "crestURI": "https://upload.wikimedia.org/wikipedia/en/e/eb/Manchester_City_FC_badge.svg", "rank": 1, "goals": 67, "goalDifference": 50, "team": "ManCity"}, {"teamId": 66, "goalsAgainst": 16, "points": 47, "playedGames": 22, "crestURI": "http://upload.wikimedia.org/wikipedia/de/d/da/Manchester_United_FC.svg", "rank": 2, "goals": 45, "goalDifference": 29, "team": "ManU"}, ...

My app.py is:

def search_team():
    import http.client
    import json

    #http://api.football-data.org/v1/teams/66
    connection = http.client.HTTPConnection('api.football-data.org')
    headers = { 'X-Auth-Token': 'c4c0ba9c685041aca2fase3d1b2fa5e585', 'X-Response-Control': 'minified' }
    connection.request('GET', '/v1/competitions/445/leagueTable', None, headers )
    response = json.loads(connection.getresponse().read().decode('utf-8'))
    json = json.dumps(response)

    return json["matchday"]

if __name__ == '__main__':
    app.run()

I'm expecting an output of: 23 but its giving me string indices must be integers exception.

Upvotes: 1

Views: 594

Answers (1)

Niema Moshiri
Niema Moshiri

Reputation: 937

You shouldn't be doing that extra json.dumps step: that creates a string that represents the JSON file, meaning your json variable is a string object (hence the error message). If you change return json["matchday"] with return response["matchday"], it should work

Upvotes: 1

Related Questions