I have some JSON data coming in, and I have it almost working. The problem is I have a record inside a record, and I want to wrap that data nicely inside a couple Python classes for encoding and decoding.
It works, if I wrap the nested JSON data as a string, but don't really want to do this because it seems like improper JSON.
Example (Works but I don't like it)
{"eventData": "{\"itemName\": \"Dflt\"}", "pID": 1}
Example (Data I would like to use)
{"eventData": {\"itemName\": \"Dflt\"}, "pID": 1}
How can I modify my code so I don't have to wrap the sub data in "quotes"
import json
from copy import deepcopy
class Event(object):
__slots__= 'itemName'
def __init__(self, itemName):
self.itemName = itemName
def encode(self):
obj = {}
obj['itemName'] = str(self.itemName)
return json.dumps(obj)
def decode(self, json_Str):
obj = json.loads(json_Str)
self.itemName = obj['itemName']
class EventPacket(object):
__slots__= 'pID', 'eventData'
def __init__(self, pID, eventData):
self.pID = pID
self.eventData = eventData
def encode(self):
obj = {}
obj['pID'] = int(self.pID)
obj['eventData'] = self.eventData.encode()
return json.dumps(obj)
def decode(self, json_Str):
obj = json.loads(json_Str)
self.pID = obj['pID']
self.eventData = obj['eventData']
defaultEvent = Event('Dflt')
defaultPacket = EventPacket(1, defaultEvent)
packet = deepcopy(defaultPacket)
print 'packet : ', packet.encode()
tempStr = '{"eventData": "{\\"itemName\\": \\"test\\"}", "pID": 2}'
packet.decode(tempStr)
print 'packet : ', packet.encode()
#desired string format
tempStr2 = '{"eventData": {\"itemName\": \"test2\"}, "pID": 3}'
packet.decode(tempStr2)
print 'packet : ', packet.encode()