You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python终端登录表单:用户注册数据无法正确存入JSON的Entries数组问题求助

Fixing JSON User Registration Save Location Issue

Hey there! Let's get that user registration data saving correctly into your Entries array instead of as a top-level entry. The core issue is how you're adding the new user data to your JSON structure—here's the breakdown and fix:

What's Going Wrong

Your write_json function uses file_data.update(new_data) which adds the new user's fields (User name, Password, ID) as top-level keys in your JSON file, right alongside the Entries array. That's why you're seeing the new user data outside the array instead of inside it.

The Fix

We need to append the new user object directly to the Entries array instead of updating the root dictionary. Here's the revised code with key improvements:

import json

def write_json(new_data, filename='entries.json'):
    with open(filename,'r+') as file:
        file_data = json.load(file)
        # Append the new user to the Entries array instead of updating the root
        file_data['Entries'].append(new_data)
        file.seek(0)
        json.dump(file_data, file, indent = 4)
        # Truncate leftover content from the original file
        file.truncate()

print('Welcome to our company!')
print('Please enter your username here to login.')
name = input('Enter name: ')

# Load entries once, using a with block to auto-close the file
with open('entries.json', 'r') as f:
    content = json.load(f)
entries = content['Entries']

user_found = False
for e in entries:
    if name == e['User name']:
        user_found = True
        print('Please enter your password.')
        password = input('Enter password: ')
        if password == e['Password']:
            print(f'Welcome, {name}! You are now logged in!')
        else:
            print('Wrong password.')
        break

if not user_found:
    print('Your name is not in the file.')
    print('You need to register.')
    new_name = input('Please enter your name: ')
    new_password = input('Please enter your password: ')
    # Keep ID as an integer (matches existing data format)
    new_id = len(entries) + 1
    new_user = {
        "User name": new_name,
        "Password": new_password,
        "ID": new_id
    }
    write_json(new_user)
    print(f"Successfully registered: {new_user}")
    print('Your details have been added to the file.')

Key Improvements Made

  • Fixed JSON Saving: Replaced file_data.update(new_data) with file_data['Entries'].append(new_data) to add the new user to the correct array.
  • Added File Truncation: file.truncate() ensures any leftover content from the original (longer) file is removed after writing the new data.
  • Cleaned Up Login Logic: Removed the unnecessary outer for c in content loop (since content is a single dictionary with one key: Entries) and used a clear user_found flag to track if the user exists.
  • Consistent Data Types: Kept the ID as an integer (matching your existing JSON data, instead of converting it to a string).

Result

After running this revised code, your entries.json will have the new user correctly nested inside the Entries array, just like your expected output:

{
    "Entries": [
        {
            "User name": "Jerry",
            "Password": "56_jerry_56",
            "ID": 1
        },
        {
            "User name": "Willy_Wonka",
            "Password": "1111",
            "ID": 2
        },
        {
            "User name": "Anita",
            "Password": "438200219",
            "ID": 3
        },
        {
            "User name": "John",
            "Password": "john1",
            "ID": 4
        },
        {
            "User name": "arya",
            "Password": "arya1",
            "ID": 5
        }
    ]
}

内容的提问来源于stack exchange,提问作者Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:52:38