Python 如何使用uuu get_uuuu使对象JSON可序列化?
我有一个decorator,它在Python 如何使用uuu get_uuuu使对象JSON可序列化?,python,json,string,python-3.x,descriptor,Python,Json,String,Python 3.x,Descriptor,我有一个decorator,它在上返回一个字符串。如何使其与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):
上返回一个字符串。如何使其与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
不可序列化。因为它不是一个真正的字符串,只是提供了一个类似字符串的接口,这并不奇怪。如何使用\uuu get\uuu
返回的值使其JSON可序列化?您需要扩展jsonecoder
类才能处理Foo
对象;示例几乎是从以下位置粘贴的副本:
foo
不可序列化的事实与Decorator
类无关。例如:A类(对象):x=3;a=a();json.dumps(a)
>>> 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"'