所以我正在制作一個讀取 json 的測驗代碼,你必須輸入要訪問的值:
import json
f = "keys.json"
data = json.loads(open(f).read())
username = input("User: ")
key = input("Key: ")
for item in data:
if item['user'] != username:
print("Incorrect username.")
elif item['key'] != key:
print("Incorrect key.")
else:
print(f"Welcome, {username}.")
這就是 json 檔案的樣子:
[
{
"id": 1,
"user": "susan",
"key": "yes"
},
{
"id": 2,
"user": "susana",
"key": "yess"
}
]
這是輸出:
User: susan
Key: yes
Welcome, susan.
Incorrect username.
它列印正確的驗證和不正確的驗證,但只列印用戶名,因為如果密鑰不正確,它會列印如下:
User: susan
Key: e
Incorrect key.
Incorrect username.
我可以做些什么來洗掉第二條訊息?
uj5u.com熱心網友回復:
成功驗證后,您不想繼續
for回圈 - 使用break命令。如果
for回圈已用盡(即沒有break執行任何命令),則表示未找到對應的記錄。使用回圈的else:分支for來通知失敗:
for item in data:
if item['user'] == username and item['key'] == key:
print(f"Welcome, {username}.")
break
else:
print("Incorrect username or key.")
筆記:
這段代碼不顯示,哪個部分不正確,因此潛在的入侵者將獲得較少的資訊。
是的,
for回圈也可能有else:分支。當(且僅當)for回圈完全耗盡時執行。
uj5u.com熱心網友回復:
原因:問題是 json 檔案中有兩個元素,當它遍歷串列時,它會為所有元素運行列印功能。
解決方案:在回圈的開頭添加一個額外的 if 檢查,以防止其他失敗案例的任何輸出。
for item in data:
# skip if username doesn't match
if item['user'] == username:
# check if password matches
if item['key'] != key:
print("Incorrect key.")
else:
print(f"Welcome, {username}.")
print("Incorrect username.")
uj5u.com熱心網友回復:
原因是當你找到一個成功的匹配時你沒有跳出回圈。但是,我建議學習內置陣列方法,例如: filter,find等。
在這種情況下,您可以通過以下方式使您的代碼更容易:
// [...] the input code is fine
// Find in data an item that has the username and key == to our inputs
var user = data.find( item => item.user == username && item.key == key )
if(user) {
print(f"Welcome, {username}")
}
else {
print("Incorrect username or key.")
}
如果您要以較舊的手動方式進行操作:
var found = false;
for item in data:
if item['user'] == username && item['key'] == key {
print (f"Welcome, {username}")
found = true;
break;
}
}
if !found
print("Incorrect username or key")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516867.html
標籤:Pythonjson
上一篇:回圈和拆分物件
