2 回答

TA貢獻1813條經驗 獲得超2個贊
使用default=lambda x: x.__dict__應該可以幫助你。它會轉換任何不可序列化的對象,你不必修改很多以前的代碼
import json
# rest of your code
with open("file.json", "w+", encoding="utf-8") as file:
json.dump(datalist, file, default=lambda x: x.__dict__) #datalist is a list in my case
編輯 :
這是我測試時的完整代碼:
import json
class Data:
def __init__(self, ticker="string", comment=[], submissions=[]):
self.ticker = ticker
self.comments = comments
self.submissions = submissions
class Comment:
def __init__(self, author_name="", body="", ups=1):
self.author_name = author_name
self.body = body
self.ups = ups
class Submission:
def __init__(self, author_name="", body="", ups=1):
self.author_name = author_name
self.body = body
self.ups = ups
comments = [Comment(ups=i) for i in range(10)]
submissions = [Submission(ups=2*i) for i in range(10)]
datalist = [Data(comment=comments, submissions=submissions) for i in range(5)]
with open("file.json", "w+", encoding="utf-8") as file:
json.dump(datalist, file, default=lambda x: x.__dict__)

TA貢獻1801條經驗 獲得超8個贊
默認情況下不能序列化類。所以要么你必須手動序列化它,就像你處理Data類一樣,要么使用自定義的 json 編碼器。
手動:
class Data:
...
def to_json(self):
res = self.__dict__
res['comments'] = self.comments.__dict__
return res
然而這個解決方案并不是很靈活,所以最好使用自定義的 JSON 編碼器,它將自動處理它在序列化過程中遇到的所有對象:
# from top of my head something like this:
from json import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, o):
# handle instance of `Data` during json.dump
if isinstance(o, Data):
return o.__dict__
# handle instance of `Comment` during json.dump
if isinstance(o, Comment):
return o.__dict__
return super().default(o)
json.dumps(data_list, cls=MyEncoder) # custom encoder should handle it
添加回答
舉報