Can't use message element with Function node

I'm having what I expect is a simple problem caused by my lack of understanding Node-Red.

I have a JSON string received via MQTT. I set the MQTT input node to output a JSON object. This is data from object detection that provides detection and bounding box info. I need to convert (do calculations) on some of the elements of the bounding box. I thought this would be simple using a Function node but I can't get it to work.

Here is the JSON object:

As a simple test I tried to copy the value of box_left into a new variable x.

This resulted in an error:
TypeError: Cannot read properties of undefined (reading 'box_left')

I used the debug node to verify that the element that I'm trying to use had the correct path i.e. payload[0].box_left

I then used a Change node to do the same thing and it worked.

I then tried to use Javascript to do a computation in the Change node and that also worked.

Apologies but being a new user I wasn't able to upload the screen captures of the change nodes and flow (limited to 2 media per post).

Can someone help point out what I'm doing wrong with the Function node?

I am using Node-Red v3.1.3 on a Raspberry Pi 4.

Thanks

Here is the Change node that worked

and the one that did the computation

AT a guess you are getting msg.payloads that do not have the required Object. Try

let x = msg.payload[0]?.box_left ?? 'No box_left value'
msg.x = x

return msg

And stick a debug.node on the output

Edit: The ?. stops the assignment creating an error and ?? returns whatever is after it in the event that there is an 'undefined' result in the previous part of the statement

Thanks that works to suppress the TypeError. You're correct in that there is no bounding box info when there is no face detection. I guess I should logically suppress the message at the source in that case. I was confused because the Change node didn't register the same error.

What you should probably do is put a switch node in before your function code - that way you can direct the flow away from your function (possibly to another function) if it for instance does not detect a face but does detect a number plate

So you can test for the value to be there in the switch node - if it is not then send it to another branch (using either Otherwise if you do nto wish to do any secondary tests - or the conditions for your other tests on the related outputs)

Craig

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