How to generate json data from template?

I have an automation:

- alias: mqtt_ha_start
  trigger:
    platform: homeassistant
    event: start
  action:
    service: mqtt.publish
    data:
      topic: homeassistant/scenes/test_room/list
      retain: true
      payload_template: "{{ state_attr('input_select.test_room','options') }}"

I would like to generate json data in payload_template. Is there any way to do it?

You could try the tojson filter.

payload_template: "{{ state_attr('input_select.test_room','options')|tojson }}"

Unfortunately tojson is not available. Tried in template Developer Tools:

Error rendering template: UndefinedError: ‘tojson’ is undefined

Try again. It’s a filter, not a function. I just tried it and it works fine.

I just tried Phil’s template and though I had to adjust it for an input_select that exists on my system it worked as advertised, generating : - “[“Day”, “Evening”, “Night”]”

Yes, it worked. I tried it as a function before. Many thanks!

1 Like