简体   繁体   中英

find common values from json file

I'm trying to find users from a JSON file that have the same "p1" as the input user, and then return the names of all of them. I'm new to coding, sorry if this code looks bad

user1 refers to the input user

async def find_common_p1(user1):
    users = await get_json()
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            return users[str(user)]["name"]


async def get_json():
    with open("the json file", "r") as f:
        users = json.load(f)
    return users

Inside the json file looks like:

{"user_1_id": {"name": "user_1", "p1": False}, 
"user_2_id": {"name": "user_2", "p1": True}, 
"user_3_id": {"name": "user_3", "p1": True}}

You are on the right track, your code:

async def find_common_p1(user1):
    users = await get_json()
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            return users[str(user)]["name"]

This will return the first user with a matching "p1". To return all users with a matching "p1" you have to remember all the users who match then return it at the end of the function. So like this

async def find_common_p1(user1):
    users = await get_json()
    users_with_matching_p1 = []
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            users_with_matching_p1.append(users[str(user)]["name"])
    
    return users_with_matching_p1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM