Publish json data through mqtt

{
    "w": [
        {
            "tag": "RESET1",
            "value": 0
        }
    ],
    "ts": "2017-12-28T12:22:21+0000"
}

I have to publish this data through mqtt but in this code value is static and I want to make value dynamic.
value tag data will come from numeric input or slider. How i make value dynamic?

Have you tried using variables inside the object, like this?

var variable = "Hello";
var staticValue = "World";

var jsonObject = {
  staticKey: staticValue,
  variableKey: variable
};

var jsonString = JSON.stringify(jsonObject);
msg.payload = jsonString;
return msg;

Then publish the jsonString via MQTT.

I tryed this but not working,

var variable =msg.payload;
var staticValue = "Tag1";

var jsonObject = {
    staticKey: staticValue,
    variableKey: variable
};

var jsonString = JSON.stringify(jsonObject);
return jsonString;

Please try this corrected version. (Sorry - I was typing too fast.)
The issue was the function needs to return an object, not a string.

var variable = msg.payload;
var staticValue = "World";

var javascriptObject = {
    staticKey: staticValue,
    variableKey: variable
};

var jsonString = JSON.stringify(javascriptObject);
msg.payload = jsonString;
return msg;
1 Like

Did you manage to try the revised version?

In fact it is not necessary to convert the javascript object to a JSON string before passing to MQTT, the MQTT node will do that for you. So this should work

var variable = msg.payload;
var staticValue = "World";

var jsonObject = {
    staticKey: staticValue,
    variableKey: variable
};

msg.payload = jsonObject;
return msg;

Though calling it jsonObject is a misnomer as it is actually a javascript object. It is not JSON, as JSON is a string.

2 Likes

Thanks Colin for pointing out my misnomer - which I have corrected in my listing above.

In the never ending debate function node or not, here using change node and jsonata you can get the same result.

3 Likes

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