-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonobject.py
48 lines (38 loc) · 1.23 KB
/
jsonobject.py
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
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 19 02:57:12 2014
@author: Jamie
"""
TITLE = 'jsonobject'
VERSION = '0.0.3'
AUTHOR = 'Jamie Paton'
import jsonpickle
import logging
jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)
class JSONObject(object):
"""
Notes
-----
subclasses should call
super(type(self), self).__init__()
to get a _type attribute in the JSON file.
"""
def save_to_file(self, filename):
logger = logging.getLogger(__name__)
logger.info('# saving json file {0}'.format(filename))
logger.debug('{0}'.format(str(self)))
json_string = jsonpickle.encode(self)
with open(filename, 'w') as jsonfile:
jsonfile.write(json_string)
@staticmethod
def load_from_file(filename):
logger = logging.getLogger(__name__)
logger.info('# loading json file {0}'.format(filename))
with open(filename, 'r') as jsonfile:
json_string = jsonfile.read()
logger.debug('{0}'.format(json_string))
return jsonpickle.decode(json_string)
def __repr__(self):
return jsonpickle.encode(self)
if __name__ == '__main__':
print ''.join([TITLE, ' v', VERSION, ' ', AUTHOR])