使用json文件保存类示例- Python

c6ubokkw  于 2022-12-30  发布在  Python
关注(0)|答案(1)|浏览(157)

这是我当前使用的类

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):  # all the properties of the class Book()
      return f'Title: {self._title}\nAuthor: {self._author}\nISBN: {self._isbn}\nGenre: {self._genre}\nNumber Of Copies: {self._numCopies}\n'

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
  }
]

目标是创建一个类示例book = Book("title","author",0,"genre",0),然后将其添加到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
   }
]

公平地说,我看到过类似的解决方案,但我不能完全理解任何东西

agxfikkp

agxfikkp1#

可以使用json.loads从JSON中获取字典,然后像在常规字典中一样添加新对象。

class Book:
    def __init__(self, title: str, author: str, isbn: int, genre: str, numCopies: int):
      ...

    def get_dict(self):
        dict_obj = {
            "title": self._title,
            "author": self._author,
            "isbn" : self._isbn,
            "genre" : self._genre,
            "numofcopies" : self.__numCopies
            }

        return dict_obj

现在调用get_dict方法获取字典就足够了,并通过“append”将其添加到列表中。

if __name__ == '__main__':
    with open('your.json', 'r') as f:
        books_json = f.read()

    books = json.loads(books_json)
    book = Book('title', 'author', 0, 'genre', 0)
    books.append(book.get_dict())

    with open('your.json', 'w') as f:
        f.write(json.dumps(books))

相关问题