I am trying to convert a python string back to an object, The problem is that my object contains other objects inside and I am not sure how to reconstruct the obj (called configuration) The simplified version of the code is as follows:
The sub classes:
import json
CONFIG_FILE_NAME = 'config.xml'
class POI:
def __init__(self, X, Y, W, H):
self.x = X
self.y = Y
self.w = W
self.h = H
class Mask:
def __init__(self, X, Y):
self.x = X
self.y = Y
The containing Class that I save as json:
class configuration:
def __init__(self, str = None):
if str == None:
self.POIs = []
self.Masks = []
else:
#str to obj#
self.__dict__=json.loads(str)
def toJason(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
And this is how I save and load:
def LoadConfig():
file = open(CONFIG_FILE_NAME, 'r')
str = file.read()
conf = configuration(str)
file.close()
return conf
def SaveConfig(conf):
file = open(CONFIG_FILE_NAME, 'w+')
str = conf.toJason()
file.write(str)
file.close()
The Problem:
#Test#
x = LoadConfig()
print("Test 1:")
print(x.POIs)
print("Test 2:")
print(x.POIs.x) #using x.POIs['x'] will work but it should work not as dictionary as configuration().POIs.x works
Output:
Test 1:
[{u'y': 0, u'h': 0, u'x': 0, u'w': 0, u'index': 0}]
Test 2:
Traceback (most recent call last):
File "/home/pi/Desktop/tracker/Configure/test.py", line 47, in <module>
print(x.POIs.x)
AttributeError: 'list' object has no attribute 'x'
it seems like the sub class was not deserialized....
I hope the problem was clear and that you can help me. Thank you!