当前位置: 首页 > news >正文

Python 将字典转换为 JSON

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

在这里插入图片描述

1、问题背景

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

以下是他尝试的代码:

class City:"""Stores city info"""def __init__(self, code, name, country, continent, timezone, coordinates, population, region):self.code = codeself.name = nameself.country = countryself.continent = continentself.timezone = timezoneself.coordinates = coordinatesself.population = populationself.region = regiondef 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 + '-' + destself.src = srcself.dest = destself.dist = distdef 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 格式。
以下是修改后的代码:

class City:"""Stores city info"""def __init__(self, code, name, country, continent, timezone, coordinates, population, region):self.code = codeself.name = nameself.country = countryself.continent = continentself.timezone = timezoneself.coordinates = coordinatesself.population = populationself.region = regiondef 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 + '-' + destself.src = srcself.dest = destself.dist = distdef 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'] = route2map_to_json('map.json', air_map)

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

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


http://www.mrgr.cn/news/22636.html

相关文章:

  • 在亚马逊云科技上利用Graviton4代芯片构建高性能Java应用(下篇)
  • Rust的常数、作用域与所有权
  • Nacos服务注册
  • Android架构组件MVVM模式的实战应用与数据绑定技巧
  • 深度置信网络(深度信念网络)DBN分类模型(二分类多分类)-MATLAB代码实现
  • 无线麦克风哪个品牌音质最好?十大音质最好的麦克风品牌推荐
  • Python画笔案例-039 绘制多角徽章
  • 开源神器!与文档聊天的魔法工具 -- kotaemon
  • 一款免费开源功能丰富的看图软件NeeView
  • GeekDesk:不只是桌面美化,更是你的时间管理与效率提升专家
  • 超级帐本(Hyperledger)
  • 大屏地图区域显示、复选框多选打点,自定义窗体信息(vue3+TS)
  • 14、Flink SQL 的 处理时间 详解
  • 【C#】命名规范
  • openGauss 数据库管理工具:DataKit 6.0 部署与配置实战
  • mysql性能优化-读写分离
  • 纷享销客生态伙伴大会北京站成功举办,共谋数智新未来
  • Android Studio偶尔打开Flutter项目没有智能提示的解决方案
  • 乳制品厂污水处理设备特点
  • 深度学习中常见的损失函数