Call service using MQTT

I would like to call a service using MQTT.
I want to send an MQTT message to my Home Assistant instance with the following JSON payload:
{ "service" : "service_to_trigger", "data" : "data_for_the_service" }

I have the following automation set up:

alias: PW service call request
description: ''
trigger:
  - platform: mqtt
    topic: pixelweather/request/call_service
condition: []
action:
  - service: '{{trigger.payload_json["service"]}}'
    data: {{{trigger.payload_json["data"]}}}
mode: single

Unfortunately, for some reason, I can’t save this automation. I’m assuming that there’s a syntax error, specifically with data: {{{trigger.payload_json["data"]}}}. This is most likely invalid syntax, but I could not find any similar example in the documentation, so I have no idea what the correct syntax would be. I don’t even know if something like this can be done. I know it would be easier if I created multiple automations for each service I want to call, but an automation like this would be universal.

This will probably pass ‘Check Configuration’.

No, it doesn’t. It appears that you cannot template data.

Logger: homeassistant.config
Source: config.py:464
First occurred: 2:15:36 PM (1 occurrences)
Last logged: 2:15:36 PM

Invalid config for [automation]: expected dict for dictionary value @ data[‘action’][0][‘data’]. Got None. (See ?, line ?).


action:
  - service: '{{trigger.payload_json["service"]}}'
    data: '{{trigger.payload_json["data"]}}'

At the bare minimum to get this to work, the value of data has to be a JSON dict. The question is if Home Assistant’s native types feature will help or hinder the interpretation of the JSON dict.

I think you will need to change the automation’s action to call a python_script and pass it the entire payload (JSON dict) as a parameter. The python_script will offer more flexibility for parsing the parameter and executing the requested service call.