[英]How do I create a data structure that will be serialized this JSON format in 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上面的字典?
有些事情應該有效:
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是一個返回類似問題的dict的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.