0

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()
4

1 回答 1

2

这是您可以做到的一种方法。实现to_dictfrom_dict功能,而不是encodedecode功能。在顶层执行 JSON 编码:

import json

class Event(object):
    __slots__= 'itemName'

    def __init__(self, itemName):
        self.itemName = itemName

    def to_dict(self):
        obj = {}
        obj['itemName'] = self.itemName
        return obj

    @classmethod
    def from_dict(cls, obj):
        e = cls(obj['itemName'])
        return e

class EventPacket(object):
    __slots__= 'pID', 'eventData' 

    def __init__(self, pID, eventData):
        self.pID = pID
        self.eventData = eventData

    def to_dict(self):
        obj = {}
        obj['pID'] = int(self.pID)
        obj['eventData'] = self.eventData.to_dict()

        return obj

    @classmethod
    def from_dict(cls, obj):
        ep = cls(obj['pID'])
        ep.eventData = Event.from_dict(obj['eventData'])
        return ep

example_event = Event('Dflt')
example_packet = EventPacket(1, example_event)

json_string = json.dumps(example_packet.to_dict())

recovered_example_packet = EventPacket.from_dict(json.loads(json_string))
于 2013-10-24T17:15:28.040 回答