【问题标题】:How to use __get__ to make object JSON serializable?如何使用 __get__ 使对象 JSON 可序列化?
【发布时间】:2014-07-25 11:53:42
【问题描述】:

我有一个装饰器,它在__get__ 上返回一个字符串。如何使其与json.dumps 兼容?

import json

class Decorator(object):
    def __init__(self, value=''):
        self.value = value
    def __set__(self, instance, value):
        self.value = value
    def __get__(self, instance, owner):
        return self.value

class Foo(object):
    decorator = Decorator()

foo = Foo('Hello World')
json.dumps(foo)

这个最小示例在json.dumps 中引发了一个异常,指出Decorator 不可序列化。因为它不是一个真正的字符串,而只是提供一个类似字符串的接口,这并不奇怪。如何使用__get__ 返回的值使其 JSON 可序列化?

【问题讨论】:

  • foo 不可序列化的事实与Decorator 类无关。例如:class A(object): x = 3; a = A(); json.dumps(a)

标签: python json string python-3.x descriptor


【解决方案1】:

您需要扩展JSONEncoder 类才能处理Foo 对象;示例几乎从documents复制粘贴:

>>> class myEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, Foo):
...             # implement your json encoder here
...             return 'foo object'
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
... 
>>> json.dumps(foo, cls=myEncoder)
'"foo object"'

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 2019-08-29
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多