How to access msg content and use "if"

Hi there, I did not find a proper tutorial for this yet:

I have an IR sensor that gives this json via MQTT:

zigbee2mqtt/IrSensor : msg.payload : string[104]
"{"battery":100,"illuminance":26,"illuminance_lux":26,"linkquality":102,"occupancy":false,"voltage":3035}"

depending on occupacy I want to send a telegram message, but I always get the "Alarm over" no matter how occupacy is set. I guess I use the if incorrectly. Function content:

let occupancy = msg.payload.occupancy;
let payload = {
    "chatId":390475709,
    "type":"message",
    "content":"init"
};

if (occupancy === true) {
    payload.content = "IR Alarm aktiv"
} else {
    payload.content = "IR Alarm over"
}
return {payload};

How to do it right? And why? And where to learn this? :slight_smile:

My first take on it would be that occupancy is not true.

Your code is:

if (occupancy === true) {
    payload.content = "IR Alarm aktiv"
} else {
    payload.content = "IR Alarm over"
}

So ONLY IF occupancy == true do you get the first message.

Try this code and see what it says:

let occupancy = msg.payload.occupancy;

node.warn(occupancy;      //  This will show you what `occupancy` is set to.

let payload = {
    "chatId":390475709,
    "type":"message",
    "content":"init"
};

if (occupancy === true) {
    payload.content = "IR Alarm aktiv"
} else {
    payload.content = "IR Alarm over"
}
return {payload};

I would start by reading - https://nodered.org/docs/user-guide/messages

to understand how messages are made up and can be accessed.

In this case you are receiving a string - you really need a JSON object - so you can either set the MQTT node to return a parsed object for you - then feed into a debug node to see what's going on - or feed into a JSON node (that will do the same thing) - then to a debug node for you to inspect...

Thank you, now I know how to debug better. It gives:

29.9.2020, 11:26:44node: SetTelegramMessagefunction : (warn)
undefined

Thank you, seems to make a lot of sense. Will do so.

I changed the mqtt output to JSON object - now I get true or false in the debug as it should be. :+1:

For clarity, you didn't change it to output JSON, you had JSON before (which is a string). You changed it so that it parses the JSON and converts it to a javascript object.

sure. Just in the node settings it says "a parsed JSON object" - thats what I wanted to tell. But I clearly see the difference between the objcect and the string expression now.

Yes, that is a bit ambiguous, it is easy to read it as outputting a JSON object, but actually it means a (JavaScript) Object created by parsing the JSON. Difficult to get complex meaning in a few words I suppose.

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