I have a python class which has been serialized in JSON.
import json
class Data:
def __init__(self):
self.ival = 45
self.fval = 0.5
self.str = 'A string'
def save(self, filename):
with open(filename, 'w') as dfile:
jstr = json.dumps(self.__dict__)
dfile.write(jstr)
def load(self, filename):
with open(filename, 'r') as dfile:
jstr = dfile.read()
jdict = json.loads(jstr)
# Save what is currently there
jsave = self.__dict__
# Restore the old stuff
self.__dict__ = jdict
# Restore the original stuff
for member in jsave.keys():
if not member in jdict:
self.__dict__[member] = jsave[member]
def scramble(self):
self.ival = 99
self.fval = 3.162
self.str = 'another'
dfilename = './data.json'
dobj = Data()
dobj.save(dfilename)
Some time later, I add another value to the class
class Data:
def __init__(self):
...
self.itwo = 2
...
dfilename = './data.json'
dobj = Data()
dobj.load(dfilename)
print(dobj.itwo)
This appears to work.
The question is, is this the best way of restoring a dictionary? I wish to restore the values that were there but keep the ones that weren't there. Is there a better way of merging dictionaries other than going through one key at a time as I have done?