Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用uuu get_uuuu使对象JSON可序列化?_Python_Json_String_Python 3.x_Descriptor - Fatal编程技术网

Python 如何使用uuu get_uuuu使对象JSON可序列化?

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

我有一个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):
        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"'