如何使类json序列化的dict

时间:2017-12-21 21:25:56

标签: python json serialization

Beforewords。我看到了How to make a class JSON serializable,但对于这种情况没有帮助。

我的小小马计划:

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))

结果:

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。我调查了上面的链接并做了这个:

class GRec:
    def __init__(self, name, act):
        self.name = name
        self.isActive = act

    def __repr__(self):
        return json.dumps(self.__dict__)

结果:

  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

我试图返回dict:

class GRec:
    def __init__(self, name, act):
        self.name = name
        self.isActive = act

    def __repr__(self):
        return self.__dict__

但它也给出了:

TypeError: __repr__ returned non-string (type dict)

PS。它现在适用于自定义“默认”:

def defJson(o):
    return o.__dict__

def main():
    gStore = GStorage()
    print(json.dumps(gStore.Groups, indent = 4, default = defJson))

但我更喜欢在类中进行序列化控制以进行序列化... 如果有可能吗?

0 个答案:

没有答案