Beforewords. I saw How to make a class JSON serializable, but it did not help for this case.
My little ponyprogram:
class GRec:
def __init__(self, name, act):
self.name = name
self.isActive = act
class GStorage:
Groups = {}
def __init__(self):
self.Groups[1] = GRec("line 1", True)
self.Groups[2] = GRec("line 2", False)
def main():
gStore = GStorage()
print(json.dumps(gStore.Groups, indent = 4))
Result:
Traceback (most recent call last):
File "SerTest.py", line 14, in main
print(json.dumps(gStore.Groups, indent = 4))
...
File "C:\Python3\lib\json\encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <GTest.GRec object at 0x0000000005DCEB38> is not JSON serializable
Ook. I investigated the above link and made this:
class GRec:
def __init__(self, name, act):
self.name = name
self.isActive = act
def __repr__(self):
return json.dumps(self.__dict__)
Result:
Unhandled exception.
Traceback (most recent call last):
File "SerTest.py", line 14, in main
print(json.dumps(gStore.Groups, indent = 4))
...
File "C:\Python3\lib\json\encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: {"isActive": true, "name": "line 1"} is not JSON serializable
I tried to return dict:
class GRec:
def __init__(self, name, act):
self.name = name
self.isActive = act
def __repr__(self):
return self.__dict__
But it also gives:
TypeError: __repr__ returned non-string (type dict)
PS. It now works with custom "default":
def defJson(o):
return o.__dict__
def main():
gStore = GStorage()
print(json.dumps(gStore.Groups, indent = 4, default = defJson))
But I prefer to have serialization control inside the class to be serialized... If it is possible?