Home > Enterprise >  How do I parse an MTTQ response to JSON in NodeJS
How do I parse an MTTQ response to JSON in NodeJS

Time:04-20

I am writing a code, which subscribes to an MQTT server, and receives a response body which contains information that I would store in a database. I have successfully subscribed, and I receive a response, which I failingly tried to parse, so as to retrieve the data I need. I have tried JSON.stringify(message) which gives an unreadable buffer. I have also tried JSON.parse(message), which returns [object Object]. What is the best way to parse the data? I would also like to convert only the 4 digits in the "data" attribute to a 32bit HEX floating point value eg "C382"=-260, from https://babbage.cs.qc.cuny.edu/ieee-754.old/32bit.html

and back to decimal.

This is an examle of the response body without parsing.

  {"devId":"493C220223030476","msgType":"rs485ValueRpt"
    "data":"0103046026C382D569","timestamp":"1650447596"}.

Here is my code

const mqtt = require('mqtt');



 const options={
     port:someport,
    username:'someusername',
    password:'somepassword',
    clientId:"randomnumber"
}



const client= mqtt.connect("mqtt://site.com", options);
var topic_list="sometopic"

client.on('connect',function () {
    client.subscribe(topic_list, function (err, granted) {
 if (err) {
  console.error(err);
  return;
 }
 console.log('Subscribed to topic: '   topic_list);
});
client.on('message',function(topic, message, packet){

   
    console.log("message is "   JSON.stringify(message));

    console.log("topic is "  topic);
});
    console.log("connected flag  "  client.connected);
})

enter image description here

also tried JSON.parse(message), which returns [object object].

CodePudding user response:

JSON.parse() only works when the input is a string

JSON.stringify() only works when the input is a JavaScript Object

The message object passed to the callback is neither, it's a Buffer. So you will need to convert the Buffer to a string first.

The following should get you an object from the message and then convert that back to a prettified string to print it out.

client.on('message',function(topic, message, packet){
    var msgObject = JSON.parse(message.toString())
    console.log("message is "   JSON.stringify(msgObject,'',2));
    console.log("topic is "  topic);
});
  • Related