我有一个复杂的类对象,我试图转换成一个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 )
2条答案
按热度按时间xuo3flqw1#
创建一个
Jsonable
混合类和一个自定义JSONEncoder。输出:
eh57zj3b2#
_wo =工作订单(子装载(_状态详细信息),子装载(_订单参考),_请求日期)
这修复了我的问题。将JSON字符串解码成字典,然后将其转换为JSON。