这是我当前使用的类
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
}
]
公平地说,我看到过类似的解决方案,但我不能完全理解任何东西
1条答案
按热度按时间agxfikkp1#
可以使用json.loads从JSON中获取字典,然后像在常规字典中一样添加新对象。
现在调用get_dict方法获取字典就足够了,并通过“append”将其添加到列表中。