最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Find element by key in json - Stack Overflow

programmeradmin5浏览0评论

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 0
Add a comment  | 

1 Answer 1

Reset to default 1

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": "[email protected]"
    },
    {
        "ID": 1,
        "login": "admin2",
        "password": "1234",
        "email": "[email protected]"
    }
]
发布评论

评论列表(0)

  1. 暂无评论