mqtt message parsing problem in a node.js

27 views Asked by At

I try to extract the state of a switch from a mqtt message I get when the switch toggles. The mqtt message I get is:

{"src":"shellyplus1-08b61fd9e540","dst":"shellyplus1-08b61fd9e540/events","method":"NotifyStatus","params":{"ts":1711558165.32,"input:0":{"id":0,"state":true}}

I need to know the value of the key "state" I tried following code

let mqtt = require('mqtt');
//Connect to the MQTT Server
let client = mqtt.connect('mqtt://localhost');
client.on("connect",function(){
        client.subscribe("shellyplus1-08b61fd9e540/events/rpc");
        console.log("connected to mqtt Server");
});
//parse Sensor message 
client.on ('message',function(topic,message,packet){
        var msgObject = JSON.parse(message.toString())
        var stringified = JSON.stringify(msgObject,'',2);
//      console.log("topic is "+ topic);
        console.log(stringified.params);        //works
        console.log(stringified.params.ts);     //works
//console.log(stringified.params."input:0");    //SyntaxError: Unexpected string
        });

I tried different ways to parse the message. I can read from the stringified object but only till the key "params" and also I can read "ts" but I have to jump to "input:0" and further to "state". There I get always an error because of the : in the key name. Or is there a different way to get the value of key "state"? Thank you in advance Joerg

Brits answer works but this is only the half way to my target. I need to extract the value of the 'state' and neither a dot notation nor the bracket notation works. ... console.log(msgObject.params["input:0"].state); console.log(msgObject.params["input:0"]["state"]); ... I get always

TypeError: Cannot read properties of undefined (reading 'state')

1

There are 1 answers

0
Brits On

The fact the JSON is being transmitted via MQTT is not really relevant; to access a property with a name that contains special characters you can use bracket notation:

const message = '{"src":"shellyplus1-08b61fd9e540","dst":"shellyplus1-08b61fd9e540/events","method":"NotifyStatus","params":{"ts":1711558165.32,"input:0":{"id":0,"state":true}}}';
var msgObject = JSON.parse(message);
console.log(msgObject.params);        // {ts: 1711558165.32, input:0: {...}}
console.log(msgObject.params.ts);     // 1711558165.32
console.log(msgObject.params["input:0"]);    // {id: 0, state: true}
console.log(msgObject.params["input:0"]["state"]); // true