2014-07-25 2 views
0

__get__에 문자열을 반환하는 데코레이터가 있습니다. json.dumps과 어떻게 호환 되나요?__get__을 사용하여 JSON을 직렬화 할 수있는 방법은 무엇입니까?

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) 

이 최소한의 예는 Decorator 직렬화 아니라고 주장 json.dumps에서 예외를 발생시킵니다. 실제 문자열이 아니기 때문에 놀라운 인터페이스가 아닌 문자열을 제공하십시오. __get__에 의해 반환 된 값을 사용하여 JSON을 직렬화 가능하게 만들려면 어떻게해야합니까?

+1

사실'foo'는'Decorator' 클래스 함께 할 아무것도있다 직렬화하지 않습니다. 예 :'클래스 A (객체) : x = 3; a = A(); json.dumps (a)' – shx2

답변

2

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"'