Sending JSON over MQTT

2,984 views
Skip to first unread message

cin...@gmail.com

unread,
Jan 29, 2015, 3:24:13 PM1/29/15
to node...@googlegroups.com
Hello,

maybe I'm just too stupid, but I'm trying to send javascript object over mqtt and it doesn't do what i want.
Here is the code from a function node:

msg.payload = {"property":1};
msg.topic = "topic/bla";
return msg;

And this is sent through a mqtt node. The output of the function node is
(Object) { "topic": "topic/bla", "payload": { "property": 1 } }
so everything seems ok. But then, when I look at the distributed message of the mqtt broker, it returns
(Object) { "topic": "topic/bla", "payload": "{\"property\":1}", "qos": 0, "retain": false, "_topic": "topic/bla" }

So instead of sending its json representation of the object, it makes a string with escape characters.

Is there a way of sending json or javascript objects through mqtt?

Thank you!

Nicholas O'Leary

unread,
Jan 29, 2015, 3:29:25 PM1/29/15
to node...@googlegroups.com
Hi,

it is working exactly as you describe you want it to.

You want the payload to be the JSON representation of {"property":1}.

Well, the JSON representation of {"property":1} is {"property":1}. As displayed in your second piece of output, the JSON string has been enclosed in double quotes. Which means it is necessary to escape the double quotes within the string - which is what you see.

Hope that helps,
Nick



--
http://nodered.org
---
You received this message because you are subscribed to the Google Groups "Node-RED" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-red+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

cin...@gmail.com

unread,
Jan 29, 2015, 3:44:46 PM1/29/15
to node...@googlegroups.com
thank you very much for your quick response. After serveral ours of looking at the wrong place, I managed it to work as I want. The problem was that my node application was not able to access payload.property and I thought this was due to the double quotes in the mqtt message. But as you told me, node red and mqtt does everything right, so i looked at the right peace of code. Now its working :-) 
Reply all
Reply to author
Forward
0 new messages