JSON{} node question

#1

Ok, I'm going to cop it for asking, but here goes anyway.

Ok, if I have a "message" and want to send it via MQTT, only the payload and topic are sent.

So I have to move things from what ever they are to the payload to use them at the other end.

I get that.

But when I was recently asking about reading output from a MQTT mode and the "format" it was suggested (and it worked) to put a JSON{} node at the output of the MQTT node.

Here's the dumb question:

Putting aside MQTT only sends the msg.payload and msg.topic, how does it matter putting it through a JSON{} node to get the format back?

data is data to the computer. I'm at a loss to how adding the JSON{} node "fixed" the problem I had.

I sent a message and it had/s a msg.payload.something and I was not "seeing" that.

Putting the JSON{} node suddenly fixed it.

I'm obviously missing something.

0 Likes

#2

The msg.payload that is emitted from the mqtt in node is always of datatype string, containing the "stringified" version of the javascript object that was sent "over the wire" using the mqtt protocol. In programming terms, this is know as marshalling the data structure. When it gets to the other end of the communication channel (tcp sockets, typically), the receiver must unmarshal the stream of characters, in order to get back the original structure.

The json node simply turns that raw string (now in JavaScript Object Notation format) back into a copy of the original JavaScript object (named msg in node-red). This re-inflated object can now be accessed inside function code as any normal js object, with properties and such. If you've ever seen "Willy Wonka and the Chocolate Factory" you can think of Mike TeeVee as the msg object, and the stream of bits transmitted through the air as JSON (although in node-red the received msg is the same size as the original ;*)

Your confusion is understandable, since Nick and the team have designed this "flowgramming" tool to hide much of the complexity of the underlying data structures -- and nodejs itself uses typeless variables, which can morph from string to object to number to function... But since this is a trap that many of us have fallen into, I'm wondering if the mqtt node itself should have an option to turn the json back into an object, similar to the way the http request node does?

2 Likes