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
} , {...
是否有这一个简单的解决方案?我一直在研究词典理解,但它似乎会非常复杂。
似乎在解析'd'中的'f','metro','fields'和'list_of_metros'变量时会遇到麻烦。难道是因为我在使用3.3.4口译员吗? – user2079802
@ user2079802,在dict理解中出现了拼写错误(冗余'f')。我修好了它。该代码可以在Python 2.x和3.x中运行。 – falsetru
@ user2079802,下面是一个工作示例(Python 3.x):http://ideone.com/H22ViI – falsetru