2014-03-04 1 views
2

클래스 개체 목록이 있습니다. 각 객체는 json으로 인코딩 될 수 있도록 사전에 추가되어야합니다. 이미 json 라이브러리와 dump 메소드를 사용해야한다고 결정했습니다. 오브젝트는 다음과 같다 : JSON으로 인코딩 된 건물 사전 - 파이썬

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