Formatting MQTT Trigger with JSON payload

I’ve read the documentation, and it’s not exactly clear (or I’m too much of a novice to understand it properly), so I’m hoping someone might be able to explain a little more about MQTT triggers with a JSON payload.

I’m using zigbee2MQTT, and there are three formats for delivery:

  • json
  • attribute
  • attribute_and_json

The ‘json’ option is formatted as a single message with all attributes in an array:

info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console', payload '{"current":0.12,"energy":141.4,"last_seen":"2023-12-31T07:37:27.940Z","linkquality":76,"power":10.4,"state":"OFF","voltage":124.42}'

The ‘attribute’ option sends each item in the array as a single message:

info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/state', payload 'OFF'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/power', payload '10.4'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/current', payload '0.12'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/voltage', payload '124.42'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/energy', payload '141.4'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/linkquality', payload '76'
info 2023-12-31 01:37:27MQTT publish: topic 'zigbee2mqtt/Console/last_seen', payload '2023-12-31T07:37:27.940Z'

The attribute_and_json option sends both in sequence, with the json coming first.

If I use the ‘attribute’ or ‘attribute_and_json’ option, I can specify the attribute in the trigger as part of the topic:

trigger:
  - platform: mqtt
    topic: zigbee2mqtt/Dining Light Switch/action
    payload: config_single
    id: config_single
  - platform: mqtt
    topic: zigbee2mqtt/Dining Light Switch/action
    payload: config_double
    id: config_double
condition: []
action:

If I use only the ‘attribute’ option, the entities seemingly don’t update their states due to how the MQTT integration parses MQTT messages. I’ve been using the 'attribute_and_json option, which seems to be working fine, but it makes my network very chatty by greatly increasing the number of messages, cluttering up the logs. I also have other non-z2m devices that only format their message as a JSON array, so my question is this:

Is it possible to parse pieces of the JSON array in the payload option of the trigger, and what would that YAML look like?

I’m aware it’s possible to template a condition, but I really don’t want to do that because it makes traces a nightmare since the automation triggers everytime a message is received on that device (or potentially more, if using wildcards).

Hey @kylepyke – did you ever get this figured out? I think the problem I am trying to solve may be very much like yours: how to parse the MQTT payload in an automation if you want to pass a variable (or two) as the payload. Knowing that answer would solve a raft of troubles trying to meld Node Red and HA.