Python Forum
Serializing Python data Correctly (JSON)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Serializing Python data Correctly (JSON)
#4
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 dataclasses 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.
JgKSuperstar likes this post
Reply


Messages In This Thread
RE: Serializing Python data Correctly (JSON) - by deanhystad - Nov-04-2021, 06:22 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why can I not see the code correctly in Python IDLE.? Trump 8 997 Apr-04-2024, 07:47 AM
Last Post: jonesphedra
  encrypt data in json file help jacksfrustration 1 530 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  Correctly read a malformed CSV file data klllmmm 2 2,340 Jan-25-2023, 04:12 PM
Last Post: klllmmm
  Read nested data from JSON - Getting an error marlonbown 5 1,611 Nov-23-2022, 03:51 PM
Last Post: snippsat
  Reading Data from JSON tpolim008 2 1,249 Sep-27-2022, 06:34 PM
Last Post: Larz60+
  Python Split json into separate json based on node value CzarR 1 6,125 Jul-08-2022, 07:55 PM
Last Post: Larz60+
  Convert nested sample json api data into csv in python shantanu97 3 3,157 May-21-2022, 01:30 PM
Last Post: deanhystad
  Struggling with Juggling JSON Data SamWatt 7 2,151 May-09-2022, 02:49 AM
Last Post: snippsat
  json api data parsing elvis 0 1,007 Apr-21-2022, 11:59 PM
Last Post: elvis
  Capture json data JohnnyCoffee 0 1,297 Nov-18-2021, 03:19 PM
Last Post: JohnnyCoffee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020