admin管理员组文章数量:1405117
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]"
}
]
本文标签: pythonFind element by key in jsonStack Overflow
版权声明:本文标题:python - Find element by key in json - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744296972a2599389.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论