EmPe Ah
EmPe Ah

Reputation: 41

How to query JSON data in python #noobie

Say I have JSON data like so:

{
    "friends": {
        "Charlie": {
            "gender": "female",
            "age": "28"
        },
        "Josh": {
            "gender": "male",
            "age": "22"
        },
        "Annie": {
            "gender": "female",
            "age": "24"
        }
    }
}

What's the best/most pythonic way to "query" all my friend's age?

I understand that I can drill into a specific dataset by calling:

var_holding_json['friends']['Josh']['age']

But I can't grasp how I can go from this to

  1. "get all my friends' age".
  2. "get all my friends' names whose age is > 22"

Thanks for any pointer!

Upvotes: 2

Views: 54

Answers (2)

Dekel
Dekel

Reputation: 62536

Assuming you pur the data in data you can use

[data['friends'][x]['age'] for x in data['friends']]

If you want to get only the names of your friends whose age > 22 you can do the following:

[x for x in data['friends'] if data['friends'][x]['age'] > 22]

Upvotes: 3

Sri
Sri

Reputation: 2318

Here is one solution assuming the json above is stored in a variable named data.

for friend in data["friends"]:
    print(data["friends"][friend]["age"])

for friend in data["friends"]:
    age = int(data["friends"][friend]["age"])
    if (age > 22):
        print(friend)

Upvotes: 2

Related Questions