How do you send JSON Object with MQTT?

Edit: Figured it out. See next comment

The short version is that I’m getting On Deck shows from the Plex API. I’m then trying to send this list of shows as an array to a MQTT sensor.

This works: = {
    topic: 'home/media/plex/short_shows',
    payload: "{\"count\":3,\"shows\":[{\"title\":\"30 Rock\"}]}"

With this, I get a lovely:


This Does Not Work:

const payload = {
    count: 3,
    shows: [{ title: '30 Rock' }]

const payloadStr = JSON.stringify(payload).replace(/"/g,'\\"'); = {
    topic: 'home/media/plex/short_shows',
    payload: payloadStr

payloadStr correctly evaluates to: "{\"count\":3,\"shows\":[{\"title\":\"30 Rock\"}]}", which is exactly the same as the manually-typed string above.

However, I get this in the dev tools:



For the life of me, I can’t figure out why I can manually type the string and it works, yet I can’t dynamically generate it. Am I doing something stupid?

Figured it out!!! = {
    topic: 'home/media/plex/short_shows',
    payload: payloadStr

payload doesn’t need escaped JSON. Instead of:

const payloadStr = JSON.stringify(payload).replace(/"/g,'\\"');

…I just need:

const payloadStr = JSON.stringify(payload);

You could just use the JSON parser node too?

1 Like

Yep! I didn’t even try that at first because I thought all the double-quotes had to be escaped to be sent through MQTT and then translated back into JSON by HASS. Guess that was wrong and I wasted wayyyy too much time on this.