Little conversion snippets for Node-RED

I was chatting with @markus (surpise you?) and we were discussing boolean and strings. Generally, in Node-RED things tend to flow better as boolean as you’re only dealing with true and false. But, in order to do that, you have to figure out how to convert these. This will convert a true or false string and make it a boolean. 3 different use cases.

only convert if it is a string and that string content is either true or false only. Otherwise do nothing.

if(msg.payload == 'true') msg.payload = true
if(msg.payload == 'false') msg.payload = false

2 only works if you know that it is always an incoming string if the sting is true, it will become true, if it is anything else, it will become false.

msg.payload = msg.payload == 'true'

if the incoming is only a boolean, then the boolean will be left alone. But, if it’s a string, then it will automatically be converted to a boolean.

msg.payload = msg.payload == true || msg.payload == 'true'

These would be created within a function. Example:

2 Likes

Other way (expandible):

conv={"true":true, "on":true, "false":false, "off": false, true:true, false:false}
var=con["true"]

Inside the square brackets you can use a variable or a msg content , of course. You can also convert null values to false, same as 0/1…

3 Likes

Using dicts this way is so neat :slight_smile: I like this approach and use it in other languages as well, like python where it can be used like a make-shift switch statement.

Here is my take on the same principle (cats and different ways etc…):

const conv={'true':true,'on':true};
msg.payload=conv[msg.payload] == true;
return msg;

A thing to note about dicts and booleans in js, when you set a dict key to a boolean it will actually use the string representation of the boolean. If you use both ‘true’ and the boolean true they are the same value and would be duplicate keys. The beauty is that it also works when referencing it, so if you try to access with the boolean true or the string ‘true’ you’ll get the same item. With that said, the above dict works also for boolean input for the previously described reason, not just the strings.

You can test the above statement with the following in a function node:

const conv={'true':1, true:2};
msg.payload=conv[msg.payload];
return msg;

In both the case of passing the boolean true and the string ‘true’ you’ll get the number 2.

1 Like

That is … true (or ‘true’ if you prefer :slight_smile: )
My bias. In python (since v3.x version) It works correctly. I rely a lot on dicts.
This Is one more reason to suspect any J* language :laughing:

Yep :stuck_out_tongue: It’s plenty of fun when developing in both languages on the same day… Can get… confusing…

Shouldn’t have read this post. You both made my head spin…
:confused: