简体   繁体   中英

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":"bar 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM