Py学习  »  Python

json。转储不使用自定义python对象

Atul • 4 年前 • 2054 次点击  

我无法在python 3中序列化自定义对象。 下面是解释和代码

packages= []
data = {
    "simplefield": "value1",
    "complexfield": packages,
}

其中packages是一个 custom object Library . Library object 下面是一个班级(我也有子班级) json.JSONEncoder 但这没有帮助)

class Library(json.JSONEncoder):
def __init__(self, name):
    print("calling Library constructor ")
    self.name = name

def default(self, object):
    print("calling default method ")
    if isinstance(object, Library):
        return {
            "name": object.name
        }
    else:
        raiseExceptions("Object is not instance of Library")

现在我打电话 json.dumps(data) 但这是一个例外。

TypeError: Object of type `Library` is not JSON serializable 

看来 "calling default method" 不是印刷的意思, Library.default 方法不被调用

有人能帮忙吗?

我还提到 Serializing class instance to JSON 但这并没有多大帮助

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128393
文章 [ 2 ]  |  最新文章 4 年前