当前位置: 首页 > 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.lryc.cn/news/433548.html

相关文章:

  • 就服务器而言,ARM架构与X86架构有什么区别?各自的优势在哪里?
  • [论文笔记]Dimensionality Reduction by Learning an Invariant Mapping
  • 链表算法题(下)
  • UE4_后期处理_后期处理材质及后期处理体积二
  • Linux系统与高效进程控制的实战技巧
  • 陈文自媒体:抖音创作者伙伴计划,你不知道的几点!
  • 便携式气象仪器的主要特点
  • 【开源风云】从若依系列脚手架汲取编程之道(四)
  • 华为 HCIP-Datacom H12-821 题库 (15)
  • MT6895(天玑8100)处理器规格参数_MTK联发科平台方案
  • 从 0 开始搞定 RAG 应用系列(第一篇):构建简单 RAG
  • 接口(Interface)和端点(Endpoint)的区别
  • 小米汽车再陷“抄袭”争议,上汽高管直言“真不要脸”
  • VS C++ 加入dump实现崩溃日志 可以再崩溃的时候使用VS调试
  • Ubuntu22.04版本左右,开机自动启动脚本
  • 中秋之美——html5+css+js制作中秋网页
  • java设计模式day03--(结构型模式:代理模式、适配器模式、装饰者模式、桥接模式、外观模式、组合模式、享元模式)
  • Golang path/filepath包详解:高效路径操作与实战案例
  • 【Shiro】Shiro 的学习教程(四)之 SpringBoot 集成 Shiro 原理
  • 多线程篇(阻塞队列- PriorityBlockingQueue)(持续更新迭代)
  • strstr函数的使用和模拟实现
  • 使用Selenium与WebDriver实现跨浏览器自动化数据抓取
  • 信创实践(3):基于x2openEuler将CentOS升级成openEuler,享受其带来的创新和安全特性
  • LEAN 类型理论之注解(Annotations of LEAN Type Theory)-- 相等类型(Equality Type)
  • Idea 创建 Maven项目的时候卡死
  • C++入门(02)简单了解C++应用程序的开发部署
  • 有了室内外一体化人行导航,你还怕迷路吗?
  • Python虚拟环境包迁移
  • 利用分布式锁在ASP.NET Core中实现防抖
  • Django+Vue3前后端分离学习(二)(重写User类)