MQTT.publish syntax

I’m struggling to understand why the following syntax doesn’t work in a mqtt.publish event test.
{“topic”:“tele/rfbridge/RESULT”, “payload”:{“RfReceived”:{“Data”:“97BB0E2”}}}

The system accepts the json format but I get the following error in HA logs:

Log Details (ERROR)
Thu Sep 20 2018 20:31:12 GMT-0500 (Central Daylight Time)

Error executing service <ServiceCall mqtt.publish (c:1ed9801b57fa446a8f3c8da11ddf8bb2): topic=tele/rfbridge/RESULT, payload=RfReceived=Data=97BB0E2, qos=0, retain=False>
Traceback (most recent call last):
File “/usr/local/lib/python3.6/site-packages/homeassistant/core.py”, line 1127, in _event_to_service_call
await service_handler.func(service_call)
File “/usr/local/lib/python3.6/site-packages/homeassistant/components/mqtt/init.py”, line 463, in async_publish_service
msg_topic, payload, qos, retain)
File “/usr/local/lib/python3.6/site-packages/homeassistant/components/mqtt/init.py”, line 554, in async_publish
self._mqttc.publish, topic, payload, qos, retain)
File “/usr/local/lib/python3.6/concurrent/futures/thread.py”, line 56, in run
result = self.fn(*self.args, **self.kwargs)
File “/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py”, line 1079, in publish
raise TypeError(‘payload must be a string, bytearray, int, float or None.’)
TypeError: payload must be a string, bytearray, int, float or None.

This is not one of the required formats for JSON

{“RfReceived”:{“Data”:“97BB0E2”}}

Presumably, it needs to be a string, so must have quotes " around it. Unfortunately, I don’t know how to escape the internal quotes, but you might try \ or using double quotes.

Edit:
I have just done some testing this because I wasn’t happy with that answer, and while pasting I noticed that the quotes you have used are not standard ascii. This might be a copy/paste error somewhere, but will definitely cause a problem if you are sending them as JSON.

Yeah, the quotes i used in HA are fine but when they are copied from this forum, they are converted. I had the same issue when I used a mqtt validation tool to analyze the code.
I hadn’t thought about escaping the quotes. I’ll give that a try.

Yeah, the editor will not allow escaping the internal data quotes.
\"{"topic":"tele/rfbridge/RESULT", "payload":{"RfReceived":{"Data":"97BB0E2"}}}\"
{"topic":"tele/rfbridge/RESULT", "payload":{"RfReceived":{\"Data\":\"97BB0E2\"}}}

I get invalid json errors.

This seems to work

{"topic":"tele/rfbridge/RESULT", "payload":"{\"RfReceived\":{\"Data\":\"97BB0E2\"}}"}

It seems that the HA parser only accepts strings, not json objects as a value

Confirmed! This does work.
I wonder if this is intended format for nested json in HA calls?

Thank you!!!

1 Like