我有大致如下的datetime.datetime對象和namedtuples嵌套Python數據結構:的Python:Json的編碼具有namedtuples嵌套數據結構,日期
from datetime import datetime as dt
from datetime import timedelta
from collections import namedtuple
nt = namedtuple('n', 'name, contact')
f1 = nt('jules', '1234')
f2 = nt('dan', '5678')
x = [
[dt.now() + timedelta(minutes=1), f1],
[dt.now() + timedelta(hours=1), f2],
]
和編碼器是這樣的:
import json
class TestEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
print json.dumps(x, cls=TestEncoder)
輸出:
[["2012-06-21T00:48:03.296381", ["jules", "1234"]],
["2012-06-21T01:47:03.296423", ["dan", "5678"]]]
我會要想打開namedtuples成類型的字典(可能使用namedtuple ._asdict()
方法),得到以下的輸出:
[["2012-06-21T00:48:03.296381", {"name":"jules", "contact":"1234"}],
["2012-06-21T01:47:03.296423", {"name":"dan", "contact":"5678"}]]
我怎麼能保持一般的數據結構,但JSON轉儲namedtuples爲http://stardict.sourceforge.net/Dictionaries.php下載?
有問題嗎? –
我已經添加了一行「我如何保留通用數據結構,但json將namedtuples轉儲爲字典?」在問題的最後,讓問題更清楚。謝謝。 – rorycl