Json payload helper for mqtt.publish

I’m currently using the json integration for an NFC to Json publisher

- alias: NFC to MQTT
  description: Send NFC Scan events to MQTT
  trigger:
  - platform: event
    event_type: tag_scanned
  action:
  - data:
      topic: nfc/{{trigger.event.context.user_id}}/{{ trigger.event.data.tag_id }}
      payload: '{{ trigger.event.data }}'
    action: mqtt.publish
  mode: single

I would like to publish the payload a json payload though currently if I do it inline, I just get a string like

{'tag_id': '8344f092-f6b1-438a-92d3-ce9143013083', 'name': 'tag_name', 'device_id': 'f23a3b4358ef41b5085b798327d26d16'}

It seems like it could be modified to support a json payload to make things easier on users.

It seems like it would be possible to do something like this to convert the payload automatically

action:
  - data:
      topic: nfc/{{trigger.event.context.user_id}}/{{ trigger.event.data.tag_id }}
      payload:
         key1: value1
         key2: value2
    action: mqtt.publish
if instanceof(dict, payload):
    payload = json.dumps(payload)

There is a |to_json filter.

See: https://www.home-assistant.io/docs/configuration/templating/#tofrom-json

Hi Paul Traylor,

You mean this?
Templating - Home Assistant.

Oh, thank you for the reply both of you! Yes, for my specific example that seems to work (just tested it now). Not sure how I missed that (though Home Assistant is a large project :laughing: )

Though in other cases, if you need to customize the payload shape, a simple to_json filter likely would not work well, and instead would have to rely on creating a manual json payload and being careful with escaping of quotes.

You can also put lists in there.

The whole point of to_json is for it to escape your json regardless of the shape. I think you have a miss conception on how it works.