MQTT syntax and best practices for the absolute beginner

Is there a general rule of thumb for MQTT message syntax, like how they are constructed? Is MQTT messages strings only or can MQTT handle json too?

From what I can gather it seems like most MQTT messages published are a format something like:


Is there always an id?

I am a little bit familiar with rest API where JSON in the body of an HTTP GET request could look like this:


Could syntax like above also pass for an MQTT published message? Or what would I need to revise to pass for MQTT syntax?

No, MQTT is text only. JSON must be serialised first. The MQTT node will do that for you.

That isn't really needed. You have wrapped the object in an array which is not normally needed.

No. Typically the TOPIC is the id.

You would normally split that into separate topics. However, it depends a lot on how you will want to use the data later.

It is, in fact, really common to have a root topic with the JSON (serialised) and separate topics "beneath" that with individual values. This gives you the greatest flexibility. But you only need to do that if you actually need the different data types. There is no hard and fast rule.

Ah thanks. So no need for the array [] brackets, I have seem to notice that on other peoples work. Thanks for the tips

THe best thing is to try to work out how you want to consume the data. That will help you decide how to output it.

But don't get too caught up in early decisions. It is very common to need to change things later. For example, in some instances, I now have a root topic with a simple value but a more comprehensive topic lower down that has a serialised JSON value. Or I might have things the other way up. And yet more cases, I'll have a bunch of nested topics with individual values.

This last one, I have some standard functions that convert an updated JavaScript object into the equivalent set of nested topics for example which can be really useful when using MQTT for driving an event-driven system. This shouldn't really be needed and one day I really will get round to writing a context/flow/global variable driver that will include an event system as well :slight_smile:

Well actually it can be anything. Text or binary, so it can handle raw images, zip files, text. Whatever.


Basically don't worry about exactly what is in the message. You can publish pretty much anything you like. Just send it to the MQTT node and it will handle it. If you give the node an object then it will convert it to JSON to send it, and if you tell the MQTT In node to parse the JSON then it will convert it back to an object for you.

See this MQTT Essentials YouTube playlist: