How to extract key names from JSON Payload in WSO2 Enterprise Integrator

Viewed 68

I'm using WSO2 EI to ingest data from the Things Network via webhooks.

The core payload format comes in something like this :

{"frm_payload": "AQDPAkMEAAAFBQcOPg==",
      "decoded_payload": {
        "humidity": 67,
        "light": 0,
        "motion": 5,
        "temperature": 20.7,
        "vdd": 3646
      }

what I want to be able to do is transform/pivot that into an array of pairs of names and values for ingesting into my SQL database, e.g.:

{
    "Sensors": [{
            "SensorName": "humidity",
            "SensorData": 67
        },
        {
            "SensorName": "light",
            "SensorData": 0
        },
        {
            "SensorName": "motion",
            "SensorData": 5
        },
        {
            "SensorName": "temperature",
            "SensorData": 20.7
        }, {
            "SensorName": "vdd",
            "SensorData": 3646
        }
    ]
}

However I won't necessarily know the key names for for the incoming JSON pairs . E.g. If I add a new sensor that is going to start reporting 'distance' I don't want to have to modify my mediators to look specifically for 'distance' in the payload , but take that key name and use it as a value for 'SensorName'

1 Answers

I think, for your case the easiest way is to use ScriptMediator like below:

<script language="js">
<![CDATA[
   var message = mc.getPayloadJSON();
   var decoded_payload = message.decoded_payload;
   var sensorsArr = [];
   for (var keyval in decoded_payload){
      sensorsArr.push({"SensorName": keyval, "SensorData": decoded_payload[keyval] });
   }
   var payload = {"Sensors": sensorsArr};                        
   mc.setPayloadJSON(payload);]]>
</script>

As the output you will get exactly what you looking for.

Related