Json message with nested value in automation mqtt template payload

Hi, I’m trying this automation:

  trigger:
    platform: numeric_state
    entity_id: sensor.living_room_t_set_cal
    above: 1
  action:
    service: mqtt.publish
    data:
      topic: "sensor/heating/living_room/master_msg"
      payload_template: '{"type": "Tset", "value": states(\'sensor.living_room_t_set_cal\')}'
        #"{\"type\": \"Tset\", \"value\": {{ sensor.living_room_t_set_cal }} }"

however, I’m failing to create the payload_template containing the value of the sensor inside of the json payload.

any hints?

Change:

    data:

to:

    data_template:

I’m not 100% certain it will fix everything … but it’s a start.

NOTE:
I’ve never seen this format before:

      payload_template:
        type: "Tset"
        value: "{{ states.sensor.living_room_t_set_cal }}"

It’s not described in the documentation. Where did you learn how to define the payload this way? I’d like to learn more about it.

Sorry @123, I just noticed your edit. I did a major edit of my original post, as I found several errors and fixed them. Now I’m just having 1 error. Will try your solution. regarding the nested payload_template, well, that was just me being inventive. it makes kind of sense, no?

It does make sense but, as you’ve discovered, it’s invalid.

Try this:

- alias: 'example 1'
  trigger:
    platform: numeric_state
    entity_id: sensor.living_room_t_set_cal
    above: 1
  action:
    service: mqtt.publish
    data_template:
      topic: "sensor/heating/living_room/master_msg"
      payload: >
        {{'{{"type": "Tset", "value": {}}}'.format(trigger.to_state.state)}}

I tested a slightly different version of it on my system and it successfully published payloads like this:

{"type": "Tset", "value": 19.0}
1 Like