Home > Back-end >  How to add a new JSON data at the end of the existing data in python
How to add a new JSON data at the end of the existing data in python

Time:11-26

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()

CodePudding user response:

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

CodePudding user response:

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()
  • Related