0

I am trying to write an object-oriented restaurant order management system, and I have started by creating two classes in separate modules: CreateFile and Employee.

The Employee class is responsible for storing information about employees in a dictionary, such as their id ,name, phone number, and role.

The CreateFile class handles the tasks of saving, creating, loading, and updating files that are stored in a JSON format. The file will contain the information of the class instances. For example, if we have an instance x of the Employee class with the following information: Employee(4245, "John", "Smith", 07956, "waiter"), this information will be passed to the Employee class, assembled into a dictionary, and then stored in a JSON file.

I have successfully implemented the loading and saving of data. However, I am currently facing challenges with the "update" functionality. My goal is to retrieve the dictionary specific to a given instance and update it. This way, when I call the update method, I can pass any class instance, load the data, and update the corresponding dictionary.

the code for both classes is as follows:

import os
import json
class CreateFile:

    def __init__(self, data, file_name, key="", value=""):
        self.data = data
        self.file_name = file_name
        self.key = key
        self.value = value

    def create_file(self, data, file_name):
        info_to_write = json.dumps(data) + "\n"
        json_file = file_name
        if os.path.exists(json_file):
            with open(json_file, "a") as file:
                file.write(info_to_write)
        else:
            with open(json_file, "w") as file:
                file.write(info_to_write)

    

    def update_file(self, key, update_value, file_name, instance):
        loaded_data = self.load(file_name)
        for dicts in loaded_data:
            if dicts.get("emp_id") == instance.get_id():
                dicts[key] = update_value

        with open(file_name, 'w') as file:
            json.dump(loaded_data, file, indent=4)

    def load(self, file_name):
        with open(file_name, 'r') as file:
            content = file.read()
            data = json.loads(content)

        return data
Json_loading import CreateFile
class Employee:

    def __init__(self, emp_id, first_name, last_name, phone_num, role):
        self.emp_id = emp_id
        self.first_name = first_name
        self.last_name = last_name
        self.phone_num = phone_num
        self.role = role
        self.loader = CreateFile({}, "employee_data.json")

    def add_employee(self):  # should i use kwarggs?
        emp_dict = {
            "emp_id": self.emp_id,
            "first_name": self.first_name,
            "last_name": self.last_name,
            "phone_num": self.phone_num,
            "role": self.role
        }
        self.loader.create_file(emp_dict, "employee_data.json")

    def update_employee(self, key, new_value, file_name, instance):
        self.loader.update_file(key, new_value, file_name, instance)

    def get_info(self):
        return self.loader.load("employee_data.json")

I attempted to load the JSON file into a list of dictionaries and iterate over the list to find the dictionary that has the same key-value pair at index 0 as the instance I'm passing in as an argument (the instance is stored as a dictionary).

However, I encountered difficulties with this approach, as it seemed to be complex and not yielding the desired results. As a result, I was unable to successfully implement this functionality.

please note that each class is in a serrate module name Employee,Json_loading. if my approach is flawed or there is a better one i appreciate any and all feedback

  • 1
    Did you consider `pickle` at all? – JonSG May 08 '23 at 13:57
  • i have. although i a bit more familiar with json. – NeedsToKnow May 08 '23 at 14:01
  • 1
    Does this answer your question? [How to make a class JSON serializable](https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable) – alec_djinn May 08 '23 at 14:02
  • `pickle` would indeed make this somewhat easier, but it's also doable with JSON if/when you want a human-readable file. However, I'd recommend thinking hard about the separation between the loading/saving code (essentially your JSON-backed ORM) and the data model itself. – AKX May 08 '23 at 14:03
  • you are reinventing the wheel, but missing important parts on the way. You want a database. Finding the correct employee on disk, once you have a few hundred will involve fetching and decoding all employee files and scan for your key linearly - databases use indexes for that. If your goal is never to scale much, you can look at Python "shelve" module (stdlib). Otherwise, just try mongoDB, for instance. – jsbueno May 08 '23 at 14:04
  • @jsbueno ... or SQLite, to be honest. MongoDB is way overkill here IMO :) – AKX May 08 '23 at 14:06
  • @alec_djinn thank you for the link but the json class method json.dump() take scare of preparing (serializing)the data. – NeedsToKnow May 08 '23 at 14:11
  • @AKX,@jsbueno since this is not really a scaled project i am trying to do this without using external DBs however you made me think of using the Pandas library to perform actions on the data and then save it to a file as needed. what do you think of this idea? – NeedsToKnow May 08 '23 at 14:13
  • @NeedsToKnow, and what's the problem with that? – alec_djinn May 08 '23 at 14:15
  • my issue is not dumping the data or loading it rather updating it. when i reload the data i get for example a list of dicts(depending on how i reload it) i now want to update the dict of instance x of class Employee. how can i find the information/dict that directly corresponds the X's saved information. – NeedsToKnow May 08 '23 at 14:15
  • @AKX: mongo would free the OP from a serliazation step, or ORM for that matter. In these "docker" days it is hard to classify something as overkill. But sure, myself would do SQLite + pickling the data, and keep redundant columns that I'd like to use as keys. But it looks like even "shelve" may work. – jsbueno May 08 '23 at 15:43

0 Answers0