我如何创建一个将在python中序列化此JSON格式的数据结构?
我有一个接受日期对象列表的函数,应该以JSON输出以下字典:我如何创建一个将在python中序列化此JSON格式的数据结构?,python,django,json,list,dictionary,Python,Django,Json,List,Dictionary,我有一个接受日期对象列表的函数,应该以JSON输出以下字典: { "2010":{ "1":{ "id":1, "title":"foo", "postContent":"bar" }, "7":{ "id":2, "title":"foo again", "postContent":"bar baz boo" } },
{
"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\u for\u date是一个函数,它返回一个类似于您问题中的dict。正是我要找的。谢谢但它仍然不够精确,一个月内我可能会有不止一个物体。本词典是否应包含列表作为其最终值?如何将其序列化为json?@the_drow,您可以使用
defaultdict(lambda:defaultdict(list))
。然后,执行d[date.year][date.month].append(info\u for\u date(date))
。这意味着每个月最终将持有一个JSON数组(一个或多个JSON对象)。