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": "[email protected]"}, {"ID": 1, "login": "admin2", "password": "1234", "email": "[email protected]"}] 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.
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": "[email protected]"}, {"ID": 1, "login": "admin2", "password": "1234", "email": "[email protected]"}] 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.
Share Improve this question asked Mar 23 at 4:48 user30028639user30028639 233 bronze badges 01 Answer
Reset to default 1First, 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": "[email protected]"
},
{
"ID": 1,
"login": "admin2",
"password": "1234",
"email": "[email protected]"
}
]