maikati
maikati

Reputation: 61

Python parsing json issue

I'm having troubles parsing a complicated json. That is it:

{
    "response": {
        "players": [
            {
                "bar": "76561198034360615",
                "foo": "49329432943232423"
            }
        ]

    }
}

My code:

url = urllib.urlopen("foobar").read()
js = json.load(url)
data = js['response']
print data['players']

The problem is that this would print the dict. What I want is to reach the key's values, like foo and bar. What I tried so far is doing data['players']['foo'] and it gives me an error that list indices should be integers, I tried of course, it didn't work. So my question is how do I reach these values? Thanks in advance.

Upvotes: 1

Views: 121

Answers (2)

eandersson
eandersson

Reputation: 26362

The problem is that players is a list of items ([ ] in json). So you need to select the first and only item in this case using [0].

print data['players'][0]['foo']

But, keep in mind that you may have more than one player, in which case you either need to specify the player, or loop through the players using a for loop

for player in data['players']:
    print player['foo']

Upvotes: 3

alexn
alexn

Reputation: 59012

data['response']['players'] is an array (as defined by the brackets ([, ]), so you need to access items using a specific index (0 in this case):

data['players'][0]['foo']

Or iterate over all players:

for player in data['response']['players']:
    print player['foo']

Upvotes: 8

Related Questions