如何使类的dict json serializab

2024-10-02 16:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在说话之前。我看到了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

哦。我调查了上面的链接,并做了如下:

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

我试着回复迪克特:

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。它现在可用于自定义“default”:

def defJson(o):
    return o.__dict__

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

但我更喜欢在要序列化的类中有序列化控件。。。 如果可能的话?你知道吗


Tags: nameselfjsondeflineactclassgroups