Python custom object must be converted to dictionary before serialize, or covert the object be serializable

import uuid
import datetime
import json
import os

class Book:
    def __init__(self,id,name,isbn,title,topic):
        self.id=id
        self.name=name
        self.isbn=isbn
        self.title=title
        self.topic=topic
    
    def __str__(self):
        return f"Id:{self.id},name:{self.name},isbn:{self.isbn},title:{self.title},topic:{self.topic}"
    
    # def to_dict(self):
    #     """Convert Book object to dictionary"""
    #     return {
    #         'id': self.id,
    #         'name': self.name,
    #         'isbn': self.isbn,
    #         'title': self.title,
    #         'topic': self.topic
    #     }
    
    def to_dict(self):
        return self.__dict__


def WriteBooksListToJson(books_list: List[Book], json_file: str):
    try:        
        books_dic=[bk.to_dict() for bk in books_list]
        jsonStr=json.dumps(books_dic,indent=4,ensure_ascii=False)
        with open(jsonFile,'w+',encoding='utf-8') as writeFile:
            writeFile.write(jsonStr)
            print(f"Successfully write {len(booksList)} books to {jsonFile}")
    except Exception as ex:
        print(ex)


booksList=[]
print(type(booksList))

jsonFile=f"Json_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.json"

arr=range(1,5000001)
for a in arr:
    booksList.append(Book(a,f"Name_{a}",f"ISBN_{a}",f"Title_{a}",f"Topic_{a}"))



WriteBooksListToJson(booksList,jsonFile)

image

 

 

image

 

posted @ 2025-11-03 21:44  FredGrit  阅读(2)  评论(0)    收藏  举报