2013-08-31 25 views
0

有沒有一種方法來序列化一個python類而不使用自定義編碼器?我已經嘗試了下面的方法,但我得到的錯誤:TypeError:你好不是JSON序列化這是奇怪的,因爲「你好」是一個字符串。如何使一個JSON對象可序列化

class MyObj(object): 

    def __init__(self, address): 
     self.address = address 

    def __repr__(self): 
     return self.address 

x = MyObj("hello") 

print json.dumps(x) 

輸出應該只是

"hello" 

回答

1

怎麼樣jsonpickle

jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.

>>> class MyObj(object): 
...  def __init__(self, address): 
...   self.address = address 
...  def __repr__(self): 
...   return self.address 
... 
>>> x = MyObj("hello") 
>>> jsonpickle.encode(x) 
'{"py/object": "__main__.MyObj", "address": "hello"}' 
+0

JSON的輸出是RESTful API的一部分,並且這種我需要仔細控制的格式。在這個例子中,輸出應該只是「你好」。 – Roberto

0
import json 

class MyObj(object): 

    def __init__(self, address): 
     self.address = address 

    def __repr__(self): 
     return self.address 

    def serialize(self, values_only = False): 
     if values_only: 
      return self.__dict__.values() 
     return self.__dict__ 

x = MyObj("hello") 

print json.dumps(x.serialize()) 
print json.dumps(x.serialize(True)) 

輸出

>>> 
{"address": "hello"} 
["hello"] 
+1

如果對象在像字典之類的其他結構內,則不起作用,如foo = {'obj':x},然後json.dumps(foo) – Roberto

相關問題