亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從包含對象子列表的 python 列表中獲取 JSON 字符串?

從包含對象子列表的 python 列表中獲取 JSON 字符串?

泛舟湖上清波郎朗 2023-06-13 17:04:40
我有一個名為 Data 的類,如下所示:class Data:    def __init__(self, ticker, comments, submissions):        self.ticker = ticker        self.comments = comments        self.submissions = submissions其中tickerastring是comments類型對象的列表Comment,submissions是類型 objectf 的列表Submission。Comment并Submission擁有自己的領域?,F在我有一個類型的對象列表Data我想遍歷列表并獲取包含所有元素的 JSON 字符串并將其打印到文件中。我的代碼:    json_string = json.dumps([ob.__dict__ for ob in data_list])    f = open("data.json", "w")    f.write(json_string)    f.close()這會引發以下類型的錯誤:TypeError: Object of type Comment is not JSON serializable我不知道我在這里做錯了什么,有人知道嗎?編輯:評論類:class Comment:def __init__(self, author_name, body, ups):    self.author_name = author_name    self.body = body    self.ups = ups所有字段都是字符串/整數
查看完整描述

2 回答

?
慕姐8265434

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__)


查看完整回答
反對 回復 2023-06-13
?
蝴蝶刀刀

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


查看完整回答
反對 回復 2023-06-13
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號