Python中JSON文件保存失败及登录系统JSON代码故障求助
Hey there! Let's work through the issues in your login/registration system code and get it running smoothly. Here are the key problems and fixes:
1. Redundant Login/Registration Prompt
Right now, after a user registers (chooses 2), you immediately ask the same prompt again. This breaks the flow—we should structure the logic so users only get asked once, and handle their choice fully before any follow-up actions.
2. Incorrect JSON Loading Method
You’re using json.loads(file) when reading the JSON file, but that’s a mistake:
json.loads()parses JSON strings- To read directly from a file object, you need
json.load(file)
This is why your login flow is throwing an uncaught error and jumping to the "Access Denied" message.
3. Overwriting Existing User Data
Every time a new user registers, you’re writing a fresh list containing only the new user, which erases all previous accounts. We need to load existing data first (if the file exists), append the new user, then save the updated list.
4. No Actual Login Validation
Right now, your login code just reads the JSON data but doesn’t check if the entered username/password match any stored account. We need to loop through the saved users and verify credentials.
5. Unsafe File Handling
Using open() without a with statement leaves room for files to stay open if errors occur. The with statement automatically closes files for you, which is cleaner and safer.
6. Overly Broad Exception Catching
Catching all exceptions with a bare except: hides useful error details. Instead, catch specific exceptions like FileNotFoundError (when the data file doesn’t exist yet) and json.JSONDecodeError (if the file has invalid JSON).
Fixed Full Code
import json def main(): while True: sign_or_log = input('If you have an account, press 1. If you need to register, press 2. To exit, press 3: ') if sign_or_log == '2': # Registration flow username = input('Please enter your new Username: ') password = input('Please enter your new Password: ') # Load existing users (or empty list if file doesn't exist) try: with open("data.json", "r") as file: users = json.load(file) except (FileNotFoundError, json.JSONDecodeError): users = [] # Add new user and save users.append({"name": username, "password": password}) with open("data.json", "w") as file: json.dump(users, file, indent=4) # indent makes JSON readable print('Thank you for creating your account!') elif sign_or_log == '1': # Login flow login_username = input('Please enter your existing username: ') login_password = input('Please enter your existing password: ') try: with open("data.json", "r") as file: users = json.load(file) except (FileNotFoundError, json.JSONDecodeError): print('No accounts found. Please register first.') continue # Verify credentials login_success = False for user in users: if user["name"] == login_username and user["password"] == login_password: login_success = True break if login_success: print('Login successful! Welcome back.') else: print('Access Denied: Invalid username or password.') elif sign_or_log == '3': print('Exiting the system. Goodbye!') break else: print('Invalid input. Please press 1, 2, or 3.') if __name__ == "__main__": main()
Key Improvements Explained:
- Added a loop so users can perform multiple actions (register, login, exit) without restarting the script
- Uses
withstatements for all file operations to ensure proper cleanup - Preserves existing user data during registration
- Actually validates login credentials against stored data
- Catches specific exceptions to provide meaningful error messages
- Formats the saved JSON with
indent=4for readability
内容的提问来源于stack exchange,提问作者JoshMann15

