我有一个具有以下内容的JSON文件:
{
"jeff": {
}
}
我想检查是否在输入中输入名称jeff,它只会打印123 我已经在python中尝试过这种方式:
import json
from pprint import pprint
with open('users.json') as f:
data = json.load(f)
print("Hi, would you like to sign up or login?")
print("Type Login for login and Signup to signup")
option= input()
if option == "Login":
unameEntry = input("Please Enter Your Username")
if unameEntry == data[unameEntry] :
print("123")
但找不到它,我在Google上四处寻找,并竭力寻找答案
答案 0 :(得分:1)
当您使用以下方法访问字典中的值时:
data[unameEntry]
字典返回data[unameEntry]
处的值。假设,正如您在示例中设置的那样,用户键入"jeff"
:在您的示例之后,字典将返回相应的值,在您的示例中为空字典。
因此,如果您的if实际在做:
"jeff" == {}
显然是False
。
您可能最想检查用户是否是字典中的键。您可以使用in
运算符来完成此操作:
unameEntry in data
由于在这里我们无权访问您的users.json
文件,因此将字典包含在代码中。另外,要检测是否在输入处理中发现错误,我将通过几个断言并扩展条件树:
data = {
"jeff": {}
}
print("Hi, would you like to sign up or login?")
print("Type Login for login and Signup to signup")
option= input()
assert option == "Login"
if option == "Login":
unameEntry = input("Please Enter Your Username")
assert unameEntry == "jeff"
if unameEntry in data:
print("Welcome %s!" % unameEntry)
else:
print("Username %s does not exist" % unameEntry)
答案 1 :(得分:0)
对您所拥有的内容进行了一些调整,并添加了一些注释以获取详细信息。这是Python的样子:
# Python3
import json
# Load json file one-liner
file_json = json.load(open("test.json", "r"))
# Since options can only be signup/login, santize them
option = input("Type Login for login and Signup to signup: ").strip().lower()
if option == "login":
# Get name entry and strip it of whitespace
name_entry = input("Please Enter Your Username: ").strip()
# Use .get() on file_json dict() object, with a default option
# of None. However, with this you actually have to add data to
# your JSON and not just a empty field
if file_json.get(name_entry, None):
print("123")
else:
print("Name: {}, not found".format(name_entry))
else:
print("unrecognized option: {}".format(option))
这是测试JSON的外观:
{
"jeff": {
"foo": "bar"
}
}
注意如何将默认值添加到"jeff"
。否则,当您获得{ }
作为"jeff"
的值时,进行查找将始终不返回任何内容