2

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!

2 Answers 2

3

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

2 Comments

This is the pythonic way :)
Yes, Sensei Miyagi - it is... :D
2

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)

3 Comments

(I've edited a second query into my question while you were already posting your answer. Thanks for your speedy response and pls excuse my "audible".)
Thank you so much, @Sri. Your incredibly quick and helpful response is most appreciated - especially since somone was equally quick to downvote my question. :( #sucksbeinganoob
No worries. Keep trying. Someone else posted a much cleaner solution using list comprehension you might want to check out.

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.