How do I create a data structure that will be serialized this JSON format in python?
I have a function that accepts a list of date objects and should output the following dictionary in JSON:
{
"2010":{
"1":{
"id":1,
"title":"foo",
"postContent":"bar"
},
"7":{
"id":2,
"title":"foo again",
"postContent":"ba开发者_如何学Cr baz boo"
}
},
"2009":{
"6":{
"id":3,
"title":"foo",
"postContent":"bar"
},
"8":{
"id":4,
"title":"foo again",
"postContent":"bar baz boo"
}
}
}
Basically I would like to access my objects by year and month number.
What code can convert a list to this format in python that can be serialized to the dictionary above in json?Something along the lines of this should work:
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)
Where info_for_date is a function that returns a dict like those in your question.
精彩评论