1

编辑:更新的代码,不再给出指定的错误

我正在尝试将以下内容编码为 json 格式:

class Map:
    """
    Storage for cities and routes
    """

    def __init__(self):
        self.cities = {}
        self.routes = {}

class Route: """ 存储路线信息 """

def __init__(self, src, dest, dist):
    self.flight_path = src + '-' + dest
    self.src = src
    self.dest = dest
    self.dist = dist

def to_json(self):
    return {'source': self.src, 'destination': self.dest, 
    'distance': self.dist}

class City: """ 存储城市信息 """

def __init__(self, code, name, country, continent, 
             timezone, coordinates, population, region):
    self.code = code
    self.name = name
    self.country = country
    self.continent = continent
    self.timezone = timezone
    self.coordinates = coordinates
    self.population = population
    self.region = region

def to_json(self):
    return {'code': self.code, 'name': self.name, 'country': self.country, 
    'continent': self.continent, 'timezone':  self.timezone, 
    'coordinates': self.coordinates, 'population': self.population, 
    'region': self.region}

我想要一个 Python 的“城市”部分对存储在 map.cities 中的所有城市信息进行编码,而一个“路线”部分对存储在 map.routes 中的所有路线信息进行编码

我的尝试:

def map_to_json(my_file, air_map):
    """
    Saves JSON Data
    """
    with open(my_file, 'w') as outfile:
        for entry in air_map.cities:
            json.dumps(air_map.cities[entry].to_json(), outfile)
        for entry in air_map.routes:
            json.dumps(air_map.routes[entry].to_json(), outfile)

    outfile.close()

其中 air_map 是地图,my_file 是文件路径。

我收到以下错误:

>    Jmap.map_to_json('Resources/map_save.json', air_map)   File
> "JSONToMap.py", line 53, in map_to_json
>     json.dumps(air_map.cities, outfile)   File "C:\Python27\lib\json\__init__.py", line 250, in dumps
>     sort_keys=sort_keys, **kw).encode(obj)   File "C:\Python27\lib\json\encoder.py", line 207, in encode
>     chunks = self.iterencode(o, _one_shot=True)   File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
>     return _iterencode(o, 0)   File "C:\Python27\lib\json\encoder.py", line 184, in default
>     raise TypeError(repr(o) + " is not JSON serializable") TypeError: <City.City instance at 0x0417FC88> is not JSON serializable
> >>>

我对 python 和 JSON 非常陌生,因此将不胜感激。

谢谢

4

1 回答 1

2

您不能直接序列化对象。试试这个:

class City:
    """
    Stores city info
    """

    def __init__(self, code, name, country, continent, 
                 timezone, coordinates, population, region):
        self.code = code
        self.name = name
        self.country = country
        self.continent = continent
        self.timezone = timezone
        self.coordinates = coordinates
        self.population = population
        self.region = region

    def to_json(self):
        return {'code': self.code, 'name': self.name,
                'country': self.country, 
                #rest of the attributes...
               }

打电话时,

json.dumps(air_map.cities.to_json(), outfile)

模型Routes也是如此。

如果你正在处理一个对象列表,你总是可以这样做:

json.dumps([city.to_json() for city in air_map.cities], outfile)

ifair_map.cities是城市列表

于 2013-10-04T02:12:05.330 回答