Python and JSON - TypeError list indices must be integers not str

前端 未结 3 902
有刺的猬
有刺的猬 2020-12-13 19:19

I am learning to use Python and APIs (specifically, this World Cup API, http://www.kimonolabs.com/worldcup/explorer)

The JSON data looks like this:

[         


        
相关标签:
3条回答
  • 2020-12-13 19:45

    First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

    After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

    0 讨论(0)
  • 2020-12-13 19:50

    You can simplify your code down to

    url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
    json_obj = urllib2.urlopen(url).read
    player_json_list = json.loads(json_obj)
    for player in readable_json_list:
        print player['firstName']
    

    You were trying to access a list element using dictionary syntax. the equivalent of

    foo = [1, 2, 3, 4]
    foo["1"]
    

    It can be confusing when you have lists of dictionaries and keeping the nesting in order.

    0 讨论(0)
  • 2020-12-13 19:56

    I solved changing

    readable_json['firstName']
    

    by

    readable_json[0]['firstName']
    
    0 讨论(0)
提交回复
热议问题