pythonjson

Find element by key in json


I want to fetch an element under the key ID in my json list that looks like this: [{"ID": 0, "login": "admin", "password": "123", "email": "apple@gmail.com"}, {"ID": 1, "login": "admin2", "password": "1234", "email": "grape@gmail.com"}] The list is in the data.json file and it’s not assigned any variable. I have a 'check' variable that takes the value of a number. I want to call the check function from ANOTHER python file.Here’s how: if "ID"==check return True.


Solution

  • First, create and save a file "fetch_data.py" with the following code:

    import json
    
    def check_id(check):
        with open("data.json", "r") as file:
            data = json.load(file)  # Read JSON list
        for item in data:
            if item.get("ID") == check:
                return True
        return False
    

    Create and save the main.py file:

    from fetch_data import check_id
    
    check = 1  #Checking if ID 1 exists
    
    if check_id(check):
        print("ID found!")
    else:
        print("ID not found!")
    

    Please ensure that data.json file contains the following data:

    [
        {
            "ID": 0,
            "login": "admin",
            "password": "123",
            "email": "apple@gmail.com"
        },
        {
            "ID": 1,
            "login": "admin2",
            "password": "1234",
            "email": "grape@gmail.com"
        }
    ]