如何在Python中将Book类实例追加保存到JSON文件
实现Book类实例追加写入JSON文件的方法
核心问题
要将自定义Book类的实例追加到现有JSON文件,需要解决两个关键点:
- 把
Book实例转换成JSON可序列化的字典格式,且键名要和现有JSON中的一致(比如JSON里是numofcopies,类里是_numCopies) - 正确读取、更新、回写JSON文件,保证格式不被破坏
具体实现步骤
1. 给Book类添加转字典方法
在Book类中新增一个方法,将实例属性转换成符合JSON格式的字典:
class Book: def __init__(self, title: str, author: str, isbn: int, genre: str, numCopies: int): self._title = title self._author = author self._isbn = isbn self._genre = genre self._numCopies = numCopies def __str__(self): return f'Title: {self._title}\nAuthor: {self._author}\nISBN: {self._isbn}\nGenre: {self._genre}\nNumber Of Copies: {self._numCopies}\n' # 新增:将实例转为符合JSON格式的字典 def to_dict(self): return { "title": self._title, "author": self._author, "isbn": self._isbn, "genre": self._genre, "numofcopies": self._numCopies # 注意键名和现有JSON一致 }
2. 编写读写JSON的逻辑
使用Python内置的json模块完成文件操作,步骤如下:
- 读取现有JSON文件,解析为Python列表
- 创建
Book实例,调用to_dict()转成字典 - 将字典追加到列表中
- 把更新后的列表写回JSON文件,保证格式美观
完整代码:
import json def append_book_to_json(book_instance, file_path): # 读取现有JSON数据,文件不存在则创建空列表 try: with open(file_path, 'r', encoding='utf-8') as f: books_list = json.load(f) except FileNotFoundError: books_list = [] # 将Book实例转为字典并追加 books_list.append(book_instance.to_dict()) # 写回JSON文件,indent参数保证格式缩进一致 with open(file_path, 'w', encoding='utf-8') as f: json.dump(books_list, f, indent=2) # 创建目标Book实例 new_book = Book("title","author",0,"genre",0) # 调用函数追加到JSON文件(替换为你的实际文件路径) append_book_to_json(new_book, "books.json")
效果验证
执行代码后,JSON文件会追加新的条目,格式与原有内容保持一致:
[ { "title": "How to love", "author": "vagabondage3", "isbn": 9832, "genre": "Comedy", "numofcopies": 2 }, { "title": "How to eat", "author": "belabor", "isbn": 2345, "genre": "Documentary", "numofcopies": 3 }, { "title": "title", "author": "author", "isbn": 0, "genre": "genre", "numofcopies": 0 } ]
内容的提问来源于stack exchange,提问作者Moustafa Abouamer
相关产品推荐
相关产品推荐

