2020-06-02 00:05:02 +12:00
|
|
|
import json
|
|
|
|
from os import path, remove
|
|
|
|
|
|
|
|
from src.errors import InvalidJSONFile
|
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2020-06-02 00:05:02 +12:00
|
|
|
class JsonFile:
|
|
|
|
""" Write and read JSON files
|
|
|
|
Use add(self,toBeAdded) to add to files
|
|
|
|
Use delete(self,*deletedKeys) to delete keys
|
|
|
|
"""
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
file_dir = ""
|
2020-06-02 00:05:02 +12:00
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
def __init__(self, file_dir):
|
|
|
|
self.file_dir = file_dir
|
|
|
|
if not path.exists(self.file_dir):
|
2021-02-25 22:32:06 +13:00
|
|
|
self.__writeToFile({}, create=True)
|
2020-06-02 00:05:02 +12:00
|
|
|
|
|
|
|
def read(self):
|
|
|
|
try:
|
2021-02-06 21:35:50 +13:00
|
|
|
with open(self.file_dir, 'r') as f:
|
2020-06-02 00:05:02 +12:00
|
|
|
return json.load(f)
|
|
|
|
except json.decoder.JSONDecodeError:
|
2021-02-06 21:35:50 +13:00
|
|
|
raise InvalidJSONFile(f"{self.file_dir} cannot be read")
|
2020-06-02 00:05:02 +12:00
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
def add(self, to_be_added, sub=None):
|
2020-06-02 00:05:02 +12:00
|
|
|
"""Takes a dictionary and merges it with json file.
|
|
|
|
It uses new key's value if a key already exists.
|
|
|
|
Returns the new content as a dictionary.
|
|
|
|
"""
|
|
|
|
data = self.read()
|
2021-02-25 22:32:06 +13:00
|
|
|
if sub:
|
2021-02-06 21:35:50 +13:00
|
|
|
data[sub] = {**data[sub], **to_be_added}
|
2021-02-25 22:32:06 +13:00
|
|
|
else:
|
2021-02-06 21:35:50 +13:00
|
|
|
data = {**data, **to_be_added}
|
2020-06-02 00:05:02 +12:00
|
|
|
self.__writeToFile(data)
|
|
|
|
return self.read()
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
def delete(self, *delete_keys):
|
2020-06-02 00:05:02 +12:00
|
|
|
"""Delete given keys from JSON file.
|
|
|
|
Returns the new content as a dictionary.
|
|
|
|
"""
|
|
|
|
data = self.read()
|
2021-02-06 21:35:50 +13:00
|
|
|
for deleteKey in delete_keys:
|
2020-06-02 00:05:02 +12:00
|
|
|
if deleteKey in data:
|
|
|
|
del data[deleteKey]
|
|
|
|
found = True
|
|
|
|
if not found:
|
|
|
|
return False
|
|
|
|
self.__writeToFile(data)
|
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
def __writeToFile(self, content, create=False):
|
2020-06-02 00:05:02 +12:00
|
|
|
if not create:
|
2021-02-06 21:35:50 +13:00
|
|
|
remove(self.file_dir)
|
|
|
|
with open(self.file_dir, 'w') as f:
|
2021-02-25 22:32:06 +13:00
|
|
|
json.dump(content, f, indent=4)
|