Automation publish mqtt message in json format

Hi

im trying to create an automation to there takes input slider state and publish at to mqtt in json format.

but i can’t find a way to publish a mqtt message in json format.

is there anyone there know how.

Maybe here ?

It isn’t clear to me exactly which part you are having trouble with, but I can offer a tip in case this is what is stopping you.

Make sure that you properly escape the quotations in the JSON payload since the MQTT publish service is already expecting JSON-formatted data. To illustrate, here is an example MQTT message to be published:

{"topic": "example/topic", "payload": "{\"key1\": \"value1\", \"key2\": \"value2\"}", "retain": "true"}
1 Like

Hi,

I worked this out the other day after a bit of trial and error. This example creates an MQTT message based on the change of state of a Nest thermostat and creates a payload with 2 values for the current and target temp. I hope it helps.

  initial_state: True
  trigger:
    platform: state
    entity_id: sensor.hallway_thermostat_temperature
  action:
    service: mqtt.publish
    data_template:
       topic: "msqto/priory/temps"
       payload: "{ \"currtemp\": {{ states.sensor.hallway_thermostat_temperature.state }}, \"targtemp\": {{states.sensor.hallway_thermostat_target.state | string }} }"

# excape characters back slash needed as above

Actually I just realised, I meant to put the String filter on the second value also, like so:

- alias: Nest Current Temp
  initial_state: True
  trigger:
    platform: state
    entity_id: sensor.hallway_thermostat_temperature
  action:
    service: mqtt.publish
    data_template:
       topic: "msqto/priory/temps"
       payload: "{ \"currtemp\": {{ states.sensor.hallway_thermostat_temperature.state | string }}, \"targtemp\": {{states.sensor.hallway_thermostat_target.state | string }} }"

# excape characters back slash needed as above

Thanks for that example, @Jerry_OR, though I had to change it a little to get it to work.

I’m not sure if I’m doing something wrong or if it’s due to a recent change, but I had to use payload_template instead of payload. With just payload, the the text “{{ states.sensor.whatever.state | string }}” gets published instead of the value.

HI @mkfink

I tested mine again this morning after your post and it is working correctly as per the code in my post. It’s a puzzle. Maybe you could post the code in your implementation so I can compare and try out your version.

I am running HA version 0.60.1 which is up to date. I am using Mosquitto as the MQTT broker.

You can avoid the escaping and readability issues if you format it like this:

- alias: Nest Current Temp
  initial_state: True
  trigger:
    platform: state
    entity_id: sensor.hallway_thermostat_temperature
  action:
    service: mqtt.publish
    data_template:
      topic: "msqto/priory/temps"
      payload: >-
        {
          "currtemp": {{ states.sensor.hallway_thermostat_temperature.state | string }},
          "targtemp": {{ states.sensor.hallway_thermostat_target.state | string }}
        }
8 Likes

Hi @NotoriousBDG, thanks a lot. That is definitely a lot better.

Isn’t this working anymore? I’ll get the following error when using your exact template:

Error executing service <ServiceCall mqtt.publish (c:954afeab76b54673957c307bfefd1bb3): topic=media, payload=cmd=play, 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.