json 我有一个关于注册系统的问题

nhaq1z21  于 2023-04-08  发布在  其他
关注(0)|答案(1)|浏览(82)

我目前正在用Python做一个注册系统。它确实工作了。它每次输入都会添加新数据。但我想让它在存在现有数据时拒绝注册过程。无论是从唯一ID,还是用户名。下面是我的代码。

# The data input from client
uniqueid = input("Please write the desired uniqueid : ")
os.system("cls")
name = input("Write your desired username : ")
os.system("cls")

# Loading up json file
with open("uniqueid.json") as fp:
    jsondata = json.load(fp)

# Appending data file
jsondata.append({
        "uniqueid" : uniqueid,
        "Name" : name,
        "Permission level" : "1"
    })

# Dumping the data
with open("uniqueid.json", 'w') as json_file:
    json.dump(jsondata, json_file, 
                        indent=4,  
                        separators=(',',': '))
bf1o4zei

bf1o4zei1#

您的代码中有几个缺陷,但这里我只是展示了一种可能的方法来检查具有uniqueid的用户是否已经注册。

with open("uniqueid.json") as fp:
    jsondata = json.load(fp)
    # you can use same syntax to check Name if you want
    if any(x for x in jsondata if x['uniqueid'] == uniqueid):
        print(f'user with {uniqueid} already registered, so denied')
        exit(0) # stop the following code execution

相关问题