2010-07-05 76 views
1

我有一個接受日期的對象列表的功能,應該輸出JSON以下字典:如何創建一個數據結構,該數據結構將在python中序列化這個JSON格式?

{ 
    "2010":{ 
     "1":{ 
     "id":1, 
     "title":"foo", 
     "postContent":"bar" 
     }, 
     "7":{ 
     "id":2, 
     "title":"foo again", 
     "postContent":"bar baz boo" 
     } 
    }, 
    "2009":{ 
     "6":{ 
     "id":3, 
     "title":"foo", 
     "postContent":"bar" 
     }, 
     "8":{ 
     "id":4, 
     "title":"foo again", 
     "postContent":"bar baz boo" 
     } 
    } 
} 

基本上我想按年份和月份數來訪問我的對象。
什麼代碼可以在Python中將列表轉換爲這種格式,可以序列化爲json上面的字典?

回答

4

沿東西這行應該工作:

from collections import defaultdict 
import json 

d = defaultdict(dict) 
for date in dates: 
    d[date.year][date.month] = info_for_date(date) 
json.dumps(d) 

哪裏info_for_date是返回像那些在你的問題中字典的功能。

+0

正是我在找的東西。謝謝。 但它仍然不夠準確,在一個月內我可能會有更多的一個對象。這本詞典應該包含列表作爲它們的最終值嗎?那將如何被序列化爲json? – 2010-07-05 09:11:54

+2

@the_drow,你可以使用'defaultdict(lambda:defaultdict(list))'。然後,做'd [date.year] [date.month] .append(info_for_date(date))''。這意味着每個月最終都會保存一個JSON數組(一個或多個JSON對象)。 – 2010-07-05 10:57:08

+0

適合我,謝謝:) – 2010-07-05 11:02:41

相關問題