Lucian Lucian - 2 months ago 7
JSON Question

Dynamic parameters in JSON serializable class

I am trying to create a JSON object with

json
library from Python 2.7. I am creating a class with needed parameters to serialize like:

class DataMessage:
channelID = 0
messageID = 0
timestamp = 0
voltageRMS = 0
currentRMS = 0
voltageDC = []
currentDC = []



But when serializing it to JSON I need the name of the parameters to change regarding channelID. For eg: when channelID=1 the data should be serialized like:

{
"messageID" = id,
"timestamp" = 32432,
"voltageRMS1" = 548,
"currentRMS1" = 5548,
"voltageDC1_1" = 43,
"voltageDC1_2" = 44,
"voltageDC1_3" = 45,
# ....
"currentDC1_1" = 32,
# ....
}


I didn't find any functionality in this library that will exclude some of the serialized parameters (
channelID
) or to dynamically create an array of
params(voltageDC[])
.

So, the details for the JSON serialised message:


  1. voltageRMS1
    - refers to the fact that
    channelID = 1

  2. voltageDC[]
    array will expand for each value in
    voltageDC_1 = ...

  3. channelID
    will not be serialized, just taken into consideration for parameters names.


kfb kfb
Answer

You will have to implement a custom JSONEncoder for your class that unpacks each array:

from json import JSONEncoder

class MyEncoder(JSONEncoder):
    def default(self, o):
        result = {
           'messageID': o.messageID,
           ...
        }

        for n, item in enumerate(o.voltageDC):
            result['voltageDC{}_{}'.format(o.channelID, n)] = item

        # and so on...

        return result

You can then call json.dumps() with your custom encoder class to get the JSON output:

dm = DataMessage()
...
json.dumps(dm, cls=MyEncoder)
Comments