Parse JSON payload from Influx DB Query

Hello Guys,

Just starting out on my Node Red journey and trying to build an intelligent solar PV switch and data logger. Switch and data logger is working fine. I'm using Influx DB to log, on a Pi Hassio platform. But having a real problem with something I thought was basic.

I got a query running which polls mean energy generation over the last 20 mins from Influx. This is the string returned.

I'm trying to get the data component highlighted. The mean valuw.

On the debug node, I'm getting "undefined".

image

This is the logic in the function node.

var arr = msg.payload;

for (var i = 0; i < arr.length; i++){
var obj = arr[i];
msg.payload = obj.mean;

}

return msg;

When posting this logic and the string in an online JS tool this code works and returns the value.

It is probably something very obvious, but I spent a lot of head scratching and got nowhere. It would be fab if you guys could take a look and maybe give me some pointers.

your return is a string, you will need to pass it through a json node to convert to an object, then mean will be at msg.payload[0].mean.

[edit Or the node that generated the string output may have an option to output an object instead.]

Thanks for this E1cid.

I thought I was already passing it through a json node. This is my flow...

image

These are the JSON node properties...

image

I'll try outputting JSON node as an object, but assume function code will need to change.

copy and paste what is going into the json node, and what is coming out, no images as the make it diffcult to copy info.

Sure, this is debug before JSON node...

array[1]
0: object
time: "2021-05-14T09:48:50.415Z"
mean: 490.9759036144578

This is debug after JSON node

string[93]
[
{
"time": "2021-05-14T09:48:50.415Z",
"mean": 490.9759036144578
}
]

remove the json node it is converting the object to a string.

Thanks again, I've done that now. What would be the best function logic to get the mean value within the array? I've seen something like this used before, but it doesn't seem to work here.

p = msg.payload[0];
node.log(typeof p);
msg.payload = p.mean;

I would use

msg.payload = msg.payload[0].mean;
returm msg;

but that could also be done in a change node very simply with out calling a function node.

1 Like

Hi E1cid, used a change node, and this has solved the problem. Many thanks for your guidance.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.