2012-08-02 16 views
1

我已經通過幾個問題解決了類似的問題,但想問一下。JSON編碼類的Python列表

我有兩個Python類,這裏簡化爲:

class Service: 
    def __init__(self): 
     self.ServiceName = None 
     self.ServiceExpDate = None 

class Provision: 
    def __init__(self): 
     self.ID = None 
     self.Type = None 
     self.Services = [] # a list of Service objects 

當我去JSON編碼提供類的一個實例:

jsonProvision = json.dumps(provision.__dict__) 

我得到正確的輸出,如果我不有任何服務,但如果它試圖序列化服務類我得到:

TypeError: <common.Service instance at 0x123d7e8> is not JSON serializable 

我需要寫一個JSON編碼器直接處理這個問題,還是有更好的方法來序列化Service類嗎?

謝謝!

回答

0

你應該編寫一個編碼器來照顧你的類,這就是json模塊的使用/擴展方式。

您嘗試對您的Provision類實例的__dict__進行編碼的嘗試現在可能會奏效,但如果您的課程發展了,那麼這種做法實際上並不是未來的證明。

1

您需要提供一個函數來將您的自定義類編碼爲default參數json.dumps()。對於類示例代碼:

import json 

class JSONEncodable(object): 
    def json(self): 
     return vars(self) 

class Service(JSONEncodable): 
    def __init__(self): 
     self.ServiceName = None 
     self.ServiceExpDate = None 

class Provision(JSONEncodable): 
    def __init__(self): 
     self.ID = None 
     self.Type = None 
     self.Services = [] # a list of Service objects 

用法示例:

>>> from operator import methodcaller 
>>> p = Provision() 
>>> p.Services.append(Service()) 
>>> print json.dumps(p, default=methodcaller("json")) 
{"Services": [{"ServiceName": null, "ServiceExpDate": null}], "Type": null, "ID": null} 

你也可以使用default=attrgetter("__dict__"),以避免對每個類別的json()方法的需要,但上述方法更加靈活。