Reputation: 1875
I have a list of class objects. Each object needs to be added to a dictionary so that it can be json encoded. I've already determined that I will need to use the json library and dump
method. The objects look like this:
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
So the json will look like this:
{
"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
} , {...
Is there a simple solution for this? I've been looking into dict comprehension but it seems it will be very complicated.
Upvotes: 2
Views: 436
Reputation: 369114
dict comprehension will not be very complicated.
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)
Upvotes: 3