Nov-04-2021, 07:31 PM
(Nov-04-2021, 04:24 PM)bowlofred Wrote: You can't append to JSON data like a log file or a database. If you want to add data to it you need to:
* read in the existing data to a list or dict
* append or add your data to that object
* dump the json again (which has all the information).
With a database you could just do the 'insert' and have it keep track of the old data. JSON can't do that.
(Nov-04-2021, 06:22 PM)deanhystad Wrote: Instead of a user list you should have a user dictionary.
This is a quick and ugly example:
import sys import json from dataclasses import dataclass @dataclass class Account(): firstName:str lastName:str email:str username:str password:str class AccountManagement: def __init__(self): self.PendingUsers = {} def CreateAccount(self, user_id, firstName, lastName, email, username, password): self.PendingUsers[user_id] = Account(firstName, lastName, email, username, password) def WriteFile(self): users = {id: user.__dict__ for id, user in self.PendingUsers.items()} json.dump(users, sys.stdout) accounts = AccountManagement() accounts.CreateAccount(1, "a", "b", "c", "d", "e") accounts.CreateAccount(2, "A", "B", "C", "D", "E") accounts.WriteFile()I think there are packages that make data dictionaries serializable. Using one of those is better than my __dict__ trick. You might also want to look at pydantic which makes a dataclass like thing that is serializeable to/from json.
Thank you very much. I also didn't know about the @dataclass decorator. I can learn about it in detail now :)