簡體   English   中英

如何在 ZA7F5F35426B927411FC3231B563821 中將 Class Object 轉換為 JSON

[英]How to convert Class Object to JSON in Python

import json

class Abc:

    firstName = ''
    secondName = ''

obj = Abc()

obj.firstName = 'Raj'

res = json.dumps(obj, default=lambda o: o.__dict__)

print(res)

Output: {"firstName": "Raj"}

但我需要像這樣的 Output

{"firstName": "Raj", "secondName": ""}

任何解決方案?

首先,從正確的 class 定義開始。

class Abc:
    def __init__(self, first='', second=''):
        self.firstName = first
        self.secondName = second

然后定義一個合適的JSONEncoder子類:

import json


class AbcEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Abc):
            return {"firstName": obj.firstName, "secondName": obj.secondName}
        return super().default(obj)


obj = Abc("Raj")
res = json.dumps(obj, cls=AbcEncoder)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM