Dynamic parameters in JSON serializable class
<p>I am trying to create a JSON object with <code>json</code> library from Python 2.7. I am creating a class with needed parameters to serialize like:</p>

<pre><code>class DataMessage:
    channelID = 0
    messageID = 0
    timestamp = 0
    voltageRMS = 0
    currentRMS = 0
    voltageDC = []
    currentDC = []
</code></pre>

<p><br>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: </p>

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

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

<p>So, the details for the JSON serialised message:</p>

<ol>
<li><code>voltageRMS1</code> - refers to the fact that <code>channelID = 1</code></li>
<li><code>voltageDC[]</code> array will expand for each value in <code>voltageDC_1 = ...</code></li>
<li><code>channelID</code> will not be serialized, just taken into consideration for parameters names.</li>
</ol>

<p>You will have to implement a custom <a href="https://docs.python.org/2/library/json.html#json.JSONEncoder" rel="nofollow"><code>JSONEncoder</code></a> for your class that unpacks each array:</p>

<pre><code>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
</code></pre>

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

<pre><code>dm = DataMessage()
...
json.dumps(dm, cls=MyEncoder)
</code></pre>

python json serialization