0

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?

Badiboy
  • 1,519
  • 1
  • 18
  • 31
  • 1
    After looking at your code for the `GRec` and `GStorage` classes, I suspect you don't really understand how classes work in Python. Regardless, see if [my answer](https://stackoverflow.com/a/18561055/355230) to a similar question which helps (after you learn more about them). – martineau Dec 21 '17 at 22:13
  • 2
    Why are you using class-variables only to shadow them? You probably just want instance variables. Further, you almost certainly don't want to use a class-level variable in `GStorage`, because every instance is sharing `Group` dict... – juanpa.arrivillaga Dec 21 '17 at 22:15
  • @juanpa.arrivillaga: I'm not too good in Python, but this was draft reduction and remaking of larger code to produce simple example, so it looks like class-variables redefinition. :) – Badiboy Dec 21 '17 at 22:34
  • @martineau: thaks for the link. I bookmarked the solution. It digs deeper that I want to, but may be there is not other variants to do what I want to. – Badiboy Dec 21 '17 at 22:37
  • 1
    Badiboy: You can definitely do what you want to do, but doing so will require properly creating (and using) the classes involved. Learning them and [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) is also a really important (crucial?) skill to acquire nowadays. – martineau Dec 21 '17 at 22:43
  • Badiboy: A good rule-of-thumb is to keep data out of your classes (in other words don't define it at the class-level). It belongs in _instances_ of classes and is usually initialized via the class's `__init__()` method and then possibly changed by the code in the class's other methods by referring to the first argument, usually called `self`, that all class method get passed to them automatically. – martineau Dec 21 '17 at 22:54

0 Answers0