MQTT Json to Influxdb (node function)

#1

Hi guys,
Need some help to improve function node that I have done to insert data into influxdb. data is coming out a Mqtt in json format.
The topic have this structure : /v1.6/devices/IOT_ID2 where "IOT_ID2" identify the device where the data is coming from.
A sample payload from one device looks like the below:
{"PreRef8":2980,"PosRRef":2980,"CurrMag":20,"MotAccu":550,"MotRpm":894,"MotFrec":3163,"Analog1":9531,"InvTemp":61,"DcLinkV":328,"StatWrd":35,"Trip0":26,"EMeter":431,"ApR1825":-25,"Vinput":26,"PowerSta":0}"

So decided to use the devices name as "measurement" requiered by influx, and all the variables included in the json would be the field.


So I created the following function that I would like to improve a bit in order to get the fields automatically from the json pairs ? any ideas how to do that ?

var tokens = msg.topic.split("/");
msg.topic=tokens[3];    // get the device id from topic /v1.6/devices/device_id
var dest = tokens[tokens.length-1];
tmp=JSON.parse(msg.payload);
var key = Object.keys(msg.payload);

msg.payload = [
    {
        measurement: msg.topic,     //Device id as topic
           fields: {
            PreRef8     :tmp.PreRef8,
            PosRRef     :tmp.PosRRef,
            CurrMag     :tmp.CurrMag,
            MotAccu     :tmp.MotAccu,
            MotRpm      :tmp.MotRpm,
            MotFrec     :tmp.MotFrec,
            Analog1     :tmp.Analog1,
            InvTemp     :tmp.InvTemp,
            DcLinkV     :tmp.DcLinkV,
            StatWrd     :tmp.StatWrd,
            Trip0       :tmp.Trip0,
            EMeter      :tmp.EMeter,
            ApR1825     :tmp.ApR1825,
            Vinput      :tmp.Vinput,
            PowerSta    :tmp.PowerSta
        
        },
        timestamp: new Date()   //insert time stamp
    },
    
];
return msg;  

that way I did it work s and this is the result below, but I would like to do it more sophisticated way , so i can feed any Json without writing manually the fields.
Thanks in advanced for any hint.

0 Likes

#2

You can simply do a for-in loop through the object.

0 Likes

#3

thanks @TotallyInformation I get help from a friend and this was the exact code that worked , just in case someone has similar need.

var tokens  = msg.topic.split("/");
msg.topic   =tokens[3];       //get device  name from topic  level 3 /v1.6/devices/tokens[3]
var dest    = tokens[tokens.length-1];
inputjson   =JSON.parse(msg.payload);

var _fields = {};
for(var item in inputjson){
    _fields[item] = inputjson[item];
}

msg.payload = [
    {
        measurement: msg.topic,     //device name as measurement
        fields: _fields,
        timestamp: new Date()
    },
    ];
return msg;
0 Likes

#4

Cool. Note that you don't need to send the timestamp, InfluxDB will do that for you.

0 Likes