Function Buffer to Outputs

#1

Hello,
I get data about an IOT hub that looks like this:
object
deviceId: "Raspberry1"
payload: buffer [43] string
{DeviceId: 2, val [1000,1000,1000,1000,1000]}
_msgid: "7a2ce875.0b8488"

Actually I'm only interested in the values between the square brackets, I want a function that leads every single value to an output.

Can someone help me?

Many Thanks
Markus

#2

Well, it looks like you have several challenges with this type of input -- it's a binary data buffer, the data does not represent a valid JSON string, and the array of values have no "names". Are you able to change the format or datatype of this input? If so, it would make it simpler to use in node-red...

If not, then here is a bit of Javascript you can put into a function node to convert the msg.payload to a string:

msg.payload = msg.payload.toString();
return msg;

(Nick/Dave: isn't there a node that will change a buffer to a string?)

Next we need to extract the id and data (assuming you will need to keep the device id, and that the data is an array of integers). One way would be to write a regular expression, and pull out the bits of text that you want... but since this string is close to being valid JSON, you can use a change node to fix the unquoted keys, and add the missing colon, like so:

image

The output should now be the valid JSON string
{"id": 2, "data": [1000,1000,1000,1000,1000]}

Wire that output to a json node, which converts that string into a JS object -- in the debug sidebar above, you can see that the payload contains the id and data array.

This recent discussion shows several good approaches for adding "labels" (or topics) to your data array elements, and to split them out for processing or display.

TCP Output Node: Needed Clarification; Please Help