-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjconf.py
More file actions
73 lines (58 loc) · 1.95 KB
/
jconf.py
File metadata and controls
73 lines (58 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import json
import os
class Jconf(object):
def __init__(self, path):
self._path = path
self._content = {}
self._raw_content = {}
if os.path.exists(self._path):
self.read()
def read(self, path=''):
# Custom path
if not path:
path = self._path
with open(path, 'r') as file:
self._raw_content = file.read()
self.json_to_dict()
def json_to_dict(self):
try:
self._content = json.loads(self._raw_content)
except json.JSONDecodeError as e:
print('Read Failed. Json decode error: {}'.format(e))
for key, value in self._content.items():
# Append leading '#' so num can be set as instance variable
if key.isdigit():
key = 'n' + str(key)
# Wizzardry Harry
setattr(self, key, value)
def write(self, path=''):
# Custom path
if not path:
path = self._path
for key, value in self.__dict__.items():
if not key.startswith('_'):
self._content[key] = value
with open(path, 'w') as file:
file.write(json.dumps(self._content))
def dict_to_json(self):
try:
self._content = json.dumps(self._raw_content)
except json.JSONDecodeError as e:
print('Json encode error:', e)
def is_empty(self):
for key, value in self.__dict__.items():
if not key.startswith('_'):
return False
return True
def keys(self):
data = []
if not self.is_empty():
for key, value in self.__dict__.items():
if not key.startswith('_'):
data.append(key)
return data
def items(self):
if not self.is_empty():
for key, value in self.__dict__.items():
if not key.startswith('_'):
yield (key, value)