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
添加回答
举报