I have a complex class object that I am trying to convert to a json array. It works, but the json is double quoted. I tried to make the class serializable using json.dumps and this function is converting it to a string.
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
Answers
_wo = WorkOrder(json.loads(_statusDetails) , json.loads(_orderRef) , _requestedDate )
this fixed my problem. Decoded json strings into dictionaries and then converted it to json.
Make a
Jsonable
mix-in class and a custom JSONEncoder.Output: