Json - Node-RED Extract

2019-06-06 06:08发布

问题:

Noob looking for help...

I have a JSON stream of data which looks like this..

{
  "header" : {
    "content" : "telegram",
    "gateway" : "EN-GW",
    "timestamp" : "2016-08-08T13:45:47.032+0100"
  },
  "telegram" : {
    "deviceId" : "01864892",
    "friendlyId" : "Boardroom-CO2-Sensor",
    "timestamp" : "2016-08-08T13:45:47.032+0100",
    "direction" : "from",
    "functions" : [ {
      "key" : "humidity",
      "value" : 39.00,
      "unit" : "%"
    }, {
      "key" : "concentration",
      "value" : 830.00,
      "unit" : "ppm"
    } ],
    "telegramInfo" : {
      "data" : "4E53820E",
      "status" : "0",
      "dbm" : -67,
      "rorg" : "A5"
    }
  }
}

From this in Node-RED i have a function node which looks like this...

return [msg.payload.telegram.functions];

Which returns these

{ "key": "concentration", "value": 830, "unit": "ppm", "_msgid": "ff5b0f47.00a4f" }

{ "key": "humidity", "value": 39, "unit": "%", "_msgid": "ff5b0f47.00a4f" }

{ "key": "temperature", "value": 26.6, "unit": "°C", "_msgid": "ef2d6de7.10d29" }

From these i would like to get a single value from each e.g. 830 for concentration. Then have it check against thresholds set by me in a node with two outputs. For example if more than 1000 output 1, less than 1000 output 2.

Is what i'm trying to achieve even possible in Node-RED??

Sorry for the possible NOOB question any help would be appreciated.

回答1:

The problem is probably that you are not returning a well formatted message object. While what you are returning from the function is a JSON object it is not conforming to Node-RED convention.

Anything you return from a function node should have a payload field if you want other nodes to be able to handle it easily.

So if you change the return to look something like this:

return { payload: msg.payload.telegram.functions }

Then downstream nodes will know to look in the msg.payload for the useful content of the message.

As for comparing keys within that message to set values and outputting different values that's relatively simple. In a new function node you could do it like this:

//check concentration exists
for (var i=0;i<msg.payload.length; i++) {
    if (msg.payload[i].concentration) {
       //more than 1000
       if (msg.payload.conentration >= 1000) {
           return {payload: 1};
       //less than 1000
       } else {
           return {payload: 0};
       }
    }
}