node.js 中的 mqtt 消息解析问题

问题描述 投票:0回答:1

我尝试从开关切换时收到的 mqtt 消息中提取开关的状态。 我收到的 mqtt 消息是:

{“src”:“shellyplus1-08b61fd9e540”,“dst”:“shellyplus1-08b61fd9e540/事件”,“方法”:“NotifyStatus”,“params”:{“ts”:1711558165.32,“输入:0”:{ “id”:0,“状态”:true}}

我需要知道关键“state”的值 我尝试了以下代码

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
        });

我尝试了不同的方法来解析消息。 我可以从字符串化对象中读取,但只能读取关键的“params”,而且我也可以读取“ts”,但我必须跳转到“input:0”并进一步跳转到“state”。由于键名称中的 : ,我总是收到错误。 或者是否有不同的方法来获取关键“状态”的值? 先感谢您 约尔格

node.js parsing mqtt
1个回答
0
投票

JSON 通过 MQTT 传输这一事实并不真正相关;要访问名称包含特殊字符的属性,您可以使用括号表示法

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}
© www.soinside.com 2019 - 2024. All rights reserved.