1

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.

2 Answers 2

8

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yeah, I forgot how to select them exactly. Thanks alot :)
3

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

1 Comment

Haha, yea I saw he was like 60s before me. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.