构建字典为JSON编码 - python

时间:2014-03-04 05:37:29

标签: python json dictionary

我有一个类对象列表。需要将每个对象添加到字典中,以便对其进行json编码。我已经确定我需要使用json库和dump方法。对象看起来像这样:

class Metro:

    def __init__(self, code, name, country, continent,
                 timezone, coordinates, population, region):
        self.code = code #string
        self.name = name #string
        self.country = country #string
        self.continent = continent #string
        self.timezone = timezone #int
        self.coordinates = coordinates #dictionary as {"N" : 40, "W" : 88}
        self.population = population #int
        self.region = region #int

所以json看起来像这样:

{
    "metros" : [
        {
            "code" : "SCL" ,
            "name" : "Santiago" ,
            "country" : "CL" ,
            "continent" : "South America" ,
            "timezone" : -4 ,
            "coordinates" : {"S" : 33, "W" : 71} ,
            "population" : 6000000 ,
            "region" : 1
        } , {
            "code" : "LIM" ,
            "name" : "Lima" ,
            "country" : "PE" ,
            "continent" : "South America" ,
            "timezone" : -5 ,
            "coordinates" : {"S" : 12, "W" : 77} ,
            "population" : 9050000 ,
            "region" : 1
        } , {...

这有一个简单的解决方案吗?我一直在研究字典理解,但它似乎会非常复杂。

1 个答案:

答案 0 :(得分:3)

dict理解不会很复杂。

import json

list_of_metros = [Metro(...), Metro(...)]

fields = ('code', 'name', 'country', 'continent', 'timezone',
          'coordinates', 'population', 'region',)

d = {
    'metros': [
        {f:getattr(metro, f) for f in fields}
        for metro in list_of_metros
    ]
}
json_output = json.dumps(d, indent=4)