0

I am trying to populate a JSON file from the user input. The users.json file is initially empty, and I was able to register the first user ("Doe_Joh"). The problem was when I ran the program and registered for the second use. The data inside got replaced by the data. What I expected was to have the data saved incrementally. How can I achieve this?

Here is my code.

import json

class User:

        def register():

            first = input("Name: ")
            last = input("Last: ")
            username = input("Username: ")
            email = input("Email: ")
            user_data = {  username: [ {
                            "fname": first, 
                            "lname": last,
                            "username": username,
                            "email": email
                           }
                            
                        ]
                   } 
            with open("users.json", "w") as outfile:
             json.dump(user_data, outfile, indent=4)
                    
  

 
user1 = User
user1.register()
3
  • You might want to open the file in append mode instead of write mode open("users.json", "a"). But the whole data won't be a json instead, it would be a json for each user one after the other. If you want a single json, you will have to read the whole file and write it again after adding the new user to the data. Commented Nov 25, 2022 at 9:07
  • Hello @Jay, Thank you for answering. I might prefer the last option. But will json.dumb be useful in that case? Commented Nov 25, 2022 at 9:17
  • The JSON format does not work that way. Commented Nov 25, 2022 at 9:38

2 Answers 2

2

You can do it in 2 ways:

Load the whole user.json, add a new user to the end of the file, and save everything.

import json
from dataclasses import dataclass


@dataclass
class User:
    f_name: str
    l_name: str
    username: str
    email: str


def save_user(user: User) -> None:
    with open("users.json", "r") as file:
        try:
            file_data = json.load(file)
        except JSONDecodeError:
            file_data = {}
        file_data[user.username] = [{
            "fname": user.f_name,
            "lname": user.l_name,
            "username": user.username,
            "email": user.email
        }]
    with open("users.json", "w") as outfile:
        json.dump(file_data, outfile, indent=4)


def register():
    first = input("Name: ")
    last = input("Last: ")
    username = input("Username: ")
    email = input("Email: ")
    user_data = User(
        f_name=first,
        l_name=last,
        username=username,
        email=email
    )
    save_user(user=user_data)


register()

Without dataclasses (as per OP's requirement):

import json


def save_user(user) -> None:
    with open("users.json", "r") as file:
        try:
            file_data = json.load(file)
        except JSONDecodeError:
            file_data = {}
        file_data[user['username']] = [{
            "fname": user['f_name'],
            "lname": user['l_name'],
            "username": user['username'],
            "email": user['email']
        }]
    with open("users.json", "w") as outfile:
        json.dump(file_data, outfile, indent=4)


def register():
    first = input("Name: ")
    last = input("Last: ")
    username = input("Username: ")
    email = input("Email: ")
    user_data = {
        "f_name": first,
        "l_name": last,
        "username": username,
        "email": email
    }
    save_user(user=user_data)


register()

Or try to open your user.json in append mode:

 with open("users.json", "a") as outfile:
                 json.dump(user_data, outfile, indent=4)

Note the "a" in the open() function.
Note: This will break your formatting in the file

Sign up to request clarification or add additional context in comments.

9 Comments

thanks for that. Opening the file in append mode inserts a new user, but the new data corrupts the JSON format
{ "Doe_Joh": [ { "fname": "John", "lname": "Doe", "username": "Doe_Joh", "email": "[email protected]" } ] }{ "sJon": [ { "fname": "Smith", "lname": "Jon", "username": "sJon", "email": "[email protected]" } ] }
Added a code example for the first option @philip-nyankena
Thank you for helping @mighty_mike. I think I will go with the second option because the task requirements kinda forbids me from importing any other module apart from json. I am now trying to figure out how to append the data without breaking the JSON format.
You don't have to use a dataclass, you can just pass a dictionary. I'll update my answer
|
0

You can make load() function that loads previously saved data.

import json
import os

data = {}


class User():

    def register(self):
        first = input("Name: ")
        last = input("Last: ")
        username = input("Username: ")
        email = input("Email: ")
        data[username] = [{
            "fname": first,
            "lname": last,
            "username": username,
            "email": email
        }
        ]
        with open("users.json", "w") as outfile:
            json.dump(data, outfile, indent=4)

    def load(self):
        global data
        with open("users.json", "r") as outfile:
            data = json.loads(outfile.read())
            print(data, type(data))
        return data


user1 = User()

if os.path.isfile("users.json"):
    user1.load()
user1.register()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.