首页 > 解决方案 > 制作命令行登录应用程序,但似乎有错误

问题描述

我正在使用这段代码:

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

我已将所有内容都转换为字符串,甚至未转换,但没有任何效果!

标签: pythonpython-3.xpython-3.9

解决方案


这是你的结构:

{
  "users": {
    "user_name": [ { "password": ... } ],
    ...
  }
}

但是您以错误的方式访问它,请按照以下步骤操作:

  1. stuff['users']dict
  2. 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']

推荐阅读