python - 制作命令行登录应用程序,但似乎有错误
问题描述
我正在使用这段代码:
import requests
import json
import urllib.request
import random
enteredUserName = str(input("\n\nEnter your username to start signing in ≥ "))
stuff = json.loads(requests.get("https://pastebin.com/raw/HJxYck9H").text)
# UserName = str(stuff['users'][enteredUserName]['username'])
if enteredUserName == "anonymous":
print("\n\nYou are logging into the public account. Password for the public account is anonymous.")
enteredPassword = str(input("\n\nEnter your password to finish signing in ≥ "))
if enteredPassword == str(stuff['users'][enteredUserName]['password']):
if enteredUserName == "anonymous":
print("\n\nHello anonymous user. Welcome to the public account.")
else:
print("\n\nHello @" + enteredUserName + ". Welcome to your account.\n\nThis is your user info. Do not give it away.\nUsername is " + enteredUserName + "\nPassword is " + enteredPassword + "\n\n")
else:
print("\n\nWrong password.")
pastebin 上的 JSON 内容为:
{
"users": {
"anonymous": [
{
"password": "anonymous"
}
],
"James123": [
{
"password": "Jam3s"
}
],
"Jack123": [
{
"password": "J@ck"
}
]
}
}
但是当我完成输入用户名和密码时,它会显示此错误:
Traceback (most recent call last):
File "~/Documents/Test/Test.py", line 17, in <module>
if enteredPassword == str(stuff['users'][enteredUserName]['password']):
TypeError: list indices must be integers or slices, not str
我已将所有内容都转换为字符串,甚至未转换,但没有任何效果!
解决方案
这是你的结构:
{
"users": {
"user_name": [ { "password": ... } ],
...
}
}
但是您以错误的方式访问它,请按照以下步骤操作:
stuff['users']
是dict
stuff['users']['user_name']
是一个list
现在您无法访问带有字符串(如stuff['users']['user_name']['password']
)的列表。
您应该访问该列表,例如:
stuff['users'][enteredUserName][0]['password']
或者for
如果您需要检查一个以上的元素
for element in stuff['users']['user_name']:
# your check here using element['password']
推荐阅读
- java - wagon-ftp "连接超时"
- java - 使用 cplex 时优化中的条件约束
- ios - 无法将来自 Alamofire GET 请求的 JSON 数据保存到函数的局部变量
- cluster-analysis - 选择不重叠的最佳质量集群
- json - Newtonsoft JsonConvert.SerializeObject 双引号
- typescript - 为什么从打字稿命名空间中导出成员并不总是需要导出?
- tensorflow - tf.datasets input_fn 在 1 个 epoch 后出现错误
- python - 在 Python 中仅分配多个函数输出之一的最快方法
- avro - Kinesis 如何支持 Avro?
- c# - 具有多重操作合同的 WCF Rest 服务