Python:类序列化:将类对象转换为JSON

mu0hgdu0  于 2023-01-22  发布在  Python
关注(0)|答案(2)|浏览(161)

我有一个复杂的类对象,我试图转换成一个json数组。它工作,但json是双引号。我试图使类序列化使用json。dumps和这个函数是转换成字符串。

import datetime as dt
import json

class StatusDetails:
    def __init__(self, Description, Value):
        self.Description = Description
        self.Value = Value
    def toJSON(self):
        return json.dumps(self, default=lambda o:o.__dict__)
        
class OrderRef:
    def __init__(self, ID, Name):       
        self.ID = ID
        self.Name = Name
    def toJSON(self):       
        return json.dumps(self, default=lambda o:o.__dict__) #this converts the OrderRef object to a String literal

class WorkOrder:    
    def __init__(self, statusDetails, orderRef, RequestedDate): 
        self.RequestedDate = RequestedDate      
        self.StatusDetails = statusDetails
        self.OrderRef= orderRef
    
listOfWO = []

_statusDetails = StatusDetails("OPEN", "OPEN").toJSON()

_orderRef = OrderRef('12345', 'SOME VALUE').toJSON() 
_requestedDate = dt.datetime.now('US/Central').isoformat()

_wo = WorkOrder(_statusDetails , _orderRef , _requestedDate )

listOfWO.append(_wo)

_WorkOrderString = json.dumps([ob.__dict__ for ob in listOfWO]) #_orderRef and __statusDetails are literal json strings rather than  json objects; how do I get the _statusDetails and _orderRef as json objects than as literal strings?
print('posting workorder json: \n' + _WorkOrderString )
xuo3flqw

xuo3flqw1#

创建一个Jsonable混合类和一个自定义JSONEncoder。

import datetime as dt
import json
from zoneinfo import ZoneInfo
# "pip install tzdata" for timezone support if needed

class Jsonable:
    def toJSON(self):
        return self.__dict__

class JsonableEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Jsonable):
            return obj.toJSON()
        return super().default(obj)

class StatusDetails(Jsonable):
    def __init__(self, Description, Value):
        self.Description = Description
        self.Value = Value
        
class OrderRef(Jsonable):
    def __init__(self, ID, Name):       
        self.ID = ID
        self.Name = Name

class WorkOrder(Jsonable):
    def __init__(self, statusDetails, orderRef, RequestedDate): 
        self.RequestedDate = RequestedDate      
        self.StatusDetails = statusDetails
        self.OrderRef = orderRef
    
listOfWO = []

_statusDetails = StatusDetails('OPEN', 'OPEN')

_orderRef = OrderRef('12345', 'SOME VALUE')
_requestedDate = dt.datetime.now(ZoneInfo('US/Central')).isoformat()

_wo = WorkOrder(_statusDetails, _orderRef, _requestedDate)

listOfWO.append(_wo)

_WorkOrderString = json.dumps(listOfWO, cls=JsonableEncoder)
print(_WorkOrderString)

输出:

[{"RequestedDate": "2023-01-20T14:32:23.181151-06:00", "StatusDetails": {"Description": "OPEN", "Value": "OPEN"}, "OrderRef": {"ID": "12345", "Name": "SOME VALUE"}}]
eh57zj3b

eh57zj3b2#

_wo =工作订单(子装载(_状态详细信息),子装载(_订单参考),_请求日期)
这修复了我的问题。将JSON字符串解码成字典,然后将其转换为JSON。

相关问题