2014-03-04 25 views
2

我有一个类对象的列表。每个对象都需要被添加到字典中,以便它可以被json编码。我已经确定我需要使用json库和dump方法。该物体看起来是这样的:建立字典是JSON编码 - python

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 
     } , {... 

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

回答

3

字典理解不会很复杂。

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) 
+0

似乎在解析'd'中的'f','metro','fields'和'list_of_metros'变量时会遇到麻烦。难道是因为我在使用3.3.4口译员吗? – user2079802

+0

@ user2079802,在dict理解中出现了拼写错误(冗余'f')。我修好了它。该代码可以在Python 2.x和3.x中运行。 – falsetru

+0

@ user2079802,下面是一个工作示例(Python 3.x):http://ideone.com/H22ViI – falsetru