How to convert a msg. string object to boolean

First of i am new to node red, but have some experience from arduino.

I am trying to controll my Phillips Hue lights with a Hue switch, that outputs the following when pressed (in this case the "on" button have been pushed):

button: 1002

name: "On"

action: "short released"

updated: "2020-01-08T12:28:17+00:00"

When i listen to msg.payload.name i get "on" and "off" respectively. How do i turn these two string values into a boolean true and false as output?

I know i should be able to do this with the function block, but i am suspecting that there should be an easier way to do this?

In a function you can do

msg.payload = (msg.payload.name === "on")  ?  true  :  false
return msg

or you can configure a Change node like this
image

which does basically the same thing but using a JSONata expression to test the value.

[Edit] Actually the statement in the function can just be
msg.payload = msg.payload.name === "on"

I could not get your suggestions to work, maybe i did something wrong?

However this function does what i need:

if(msg.payload.name === "On"){
msg.payload = true;
}
if(msg.payload.name === "Off"){
msg.payload = false;
}
return msg;

But if anyone has a more elegant way i would like to try that :slight_smile:

1 Like

In his examples he had "on" rather than the "On" you show in yours... did you try his with "On" instead ?

ahh nice spottet.... now it works... sort of. Problem here being that there are 4 buttons (On, Off, Dim, Bright). This means that Dim and Bright are also reported as Off, using the first suggestions.

Have a look at the javascript switch statement
https://www.w3schools.com/js/js_switch.asp

In my defence you did say 'When i listen to msg.payload.name i get "on" and "off" respectively'. I had not noticed that this was inconsistent with data a few lines earlier.

1 Like

Try to use (msg.payload.name. toLowerCase()===“on”) or

switch (msg.payload.name.toLowerCase()) {
 case “on”:
  break;
 case “off”:
  break;
}

to avoid this kind of problems

1 Like

Ahh yes that is a nice way to avoid that.

Thank you for all the replies :smiley:

Hi Colin.

Thank you for your reply. I was in no way suggesting that you had anyway of knowing that there were 4 cases. You did answer correctly with the info given by me... i just recaped why i ended up not using your suggestion, because i forgot to mention the full case :slight_smile:

Just wanted to jump in and say thanks to everyone!

I've been using Node-RED with my raspberry pi for awhile using MQTT to control LED lights and a solar powered container watering system. Got stuck when trying Peter Scargills Big Timer which outputs a string to my node-RED Dashboard switch which needed a boolean.

I chose the Change node and need to take some time to learn to use the function node