开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜