[SOLVED] Nodered - Looking for a smart solution to grab JSON object elements based on time


I am using nodered to grab weather data from an API (provider is meteoblue). The JSON Object consists of arrays where the first 24 elements in each array represent the 24 hours of the current day. I am looking for a solution to poll the API every hour to populate openhab items with temperature, felttemperature and humidity from the API.

I figured out how to poll the API and populate the items:

Here is the node that writes the data at 1pm (13:00)

To cover all 24 hours my only idea is to copy this flow 24 times and start it at every hour with the corresponding array values “hard coded”:

Is there any better way to handle this? I am thinking about a variable that is checks the current hour and is used in the payload.

I hope I explained myself well enough as I am new to nodered and APIs :slight_smile:

You can absolutely do that in a function node.

You also should not need to copy the flow 23 times to run every hour, you can set a re-occurring schedule on the inject node.


Thanks. I am aware of the inject node. The problem I have is that the change node needs to use a different parameter to filter the payload depending on the current hour.

At 11.01 the payload filter is payload.data_1h.temperature[11]
At 13.01 the payload filter is payload.data_1h.temperature[13]

This is why I copy it several times and hardcode the payload.

Vincent mentioned the function node can handle this so I will do some more research about it. Any more details are highly appreciated :wink:

I am trying to get this optimized with the function node. Do you think this will work conceptually? I am not sure about the right syntax for the variable n in the []

var d = new Date();
n = d.getHours();
msg.payload = msg.payload.data_1h.temperature[**n**]
return msg;
1 Like

Conceptualisation, yes. You’ll have to check that syntax, though.

A function would be the way to go to lower the number of nodes in the flow, it took me a few weeks before I stumbled upon the repeat option on the inject node; glad you already knew about it!

If the function gives too much trouble you could use a time limit node (duplicated of course) and it would only allow the inject flow through at the specified time you wanted, not ideal it would allow for you to start collecting this information/data while you worked on the function node.

I made it finally work. Here is the solution:

var d = new Date();
n = d.getHours();
var temp = { payload: msg.payload.data_1h.temperature[n] };
var felt = { payload: msg.payload.data_1h.felttemperature[n] };
var relhumidity = { payload: msg.payload.data_1h.relativehumidity[n] };
return [temp, felt, relhumidity];

I use 24 trigger actions to make sure the flow is processed exactly at the same time every hour.

Have a look at the node-red-contrib-big-timer That should be able to replace your 24 inject nodes
If not there is a cron node too.