1

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!

Daniel Kuv
  • 21
  • 2
  • Can you post the contents of `config.xml` please? Or a generalized version of the contents that results in the same problem. – jeremye Sep 05 '17 at 12:27
  • `x.POIs` is a list so it will never have a `.x` attribute, `x.POIs[0]` is I believe the one in question – Tadhg McDonald-Jensen Sep 05 '17 at 12:37
  • Of course the subclass wasn't deserialized, when you serialize it as a plain dictionary then don't do anything to put it back into `POI` objects it will end up as plain dictionaries. to get back objects you should consider looking here: https://stackoverflow.com/a/8614096/5827215 – Tadhg McDonald-Jensen Sep 05 '17 at 12:39
  • 2
    BTW, `Jason` is someone's name. `JSON` is the data format. Anyway, what's wrong with keeping it XML serialized? – OneCricketeer Sep 05 '17 at 12:42

0 Answers0