0

I am publishing simple JSON string {"TMP":"-15.5826"} to the web client. Message appears in message.payloadString I can print it to in html but I could not parse the message with JSON.parse(). obj and data is undefined..this is the main problem, to solve this I used JSON.stringify() first, this time message parsed but data is still undefined. It seems stringify adds extra double quotes and invalidates json string. mqttws31.js is the latest, broker is mosquitto 1.4.4. What should I do to get JSON.parse() working?

publishing is through mosquitto command:mosquitto_pub -t /main/SENSOR -m {"TMP":"-15.5826"}

function onMessageArrived(message) {

    var topic = message.destinationName;
    var payload = message.payloadString;

    $('#ws').prepend('<li class=messagelist>' + topic + ' = ' + payload + '</li>');

    var jsonString = JSON.stringify(payload);

    obj = JSON.parse(jsonString); //parse with extra double quotes
    //obj = JSON.parse(payload);  //does not parse

    var data = obj.TMP;
    alert(data);
};

1 Answers1

0

You need to prevent your shell from removing the double quotes during publishing, by using single quotes around the JSON string:

mosquitto_pub -t /main/SENSOR -m '{"TMP":"-15.5826"}'

When that's done, you can use JSON.parse(payload) (no need for JSON.stringify()).

robertklep
  • 198,204
  • 35
  • 394
  • 381