Python 将字典转换为 JSON

2024-09-09 10:40:03 浏览数 (3)

在 Python 中,可以使用 json 模块将字典转换为 JSON 格式的字符串。该模块提供了 json.dumps() 方法,用于将 Python 对象(如字典、列表)序列化为 JSON 字符串。

1、问题背景

用户想要将一个 Python 字典转换为 JSON 格式,但是遇到了一个错误,错误信息提示对象 CityRoute 不可序列化。

以下是他尝试的代码:

代码语言:javascript复制
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, 
        'continent': self.continent, 'timezone':  self.timezone, 
        'coordinates': self.coordinates, 'population': self.population, 
        'region': self.region}
​
class Route:
    """
    Stores route info
    """
    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}
​
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()

2、解决方案

为了解决问题,用户需要使用 to_json() 方法将每个对象转换为一个字典,然后再使用 json.dumps() 方法将字典转换为 JSON 格式。 以下是修改后的代码:

代码语言:javascript复制
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, 
        'continent': self.continent, 'timezone':  self.timezone, 
        'coordinates': self.coordinates, 'population': self.population, 
        'region': self.region}
​
class Route:
    """
    Stores route info
    """
    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}
​
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 = Map()
city1 = City('ABC', 'City1', 'Country1', 'Continent1', 'Timezone1', 'Coordinates1', 100000, 'Region1')
city2 = City('DEF', 'City2', 'Country2', 'Continent2', 'Timezone2', 'Coordinates2', 200000, 'Region2')
city3 = City('GHI', 'City3', 'Country3', 'Continent3', 'Timezone3', 'Coordinates3', 300000, 'Region3')
route1 = Route('ABC','DEF', 100)
route2 = Route('DEF','GHI', 200)
air_map.cities['ABC'] = city1
air_map.cities['DEF'] = city2
air_map.cities['GHI'] = city3
air_map.routes['ABC-DEF'] = route1
air_map.routes['DEF-GHI'] = route2
​
map_to_json('map.json', air_map)

运行该代码后,就可以将字典转换为 JSON 格式并保存到文件中。

上面就是今天我要讲的全部内容,详细并完整的记录了,如果有任何问题大家都可以联系我。

0 人点赞