skip to Main Content

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


  1. Chosen as BEST ANSWER

    _wo = WorkOrder(json.loads(_statusDetails) , json.loads(_orderRef) , _requestedDate )

    this fixed my problem. Decoded json strings into dictionaries and then converted it to json.


  2. Make a Jsonable mix-in class and a custom 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)
    

    Output:

    [{"RequestedDate": "2023-01-20T14:32:23.181151-06:00", "StatusDetails": {"Description": "OPEN", "Value": "OPEN"}, "OrderRef": {"ID": "12345", "Name": "SOME VALUE"}}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search