JSON map in data_template

I’m trying to control switches etc in HA by sending MQTT messages to HA. I have this automation rule:

- alias: Control switches via MQTT
  trigger:
    platform: mqtt
    topic: homeassistant/to-ha/cmd
  action:
    - service_template: "{{ trigger.payload_json['service'] }}"
      data_template: >
        {{ trigger.payload_json['data'] }}

The payload of my message is going to look like this:

{
  "service": "light.turn_off",
  "data": {
    "entity_id": "group.kitchen_lights"
  }
}

But this is not right. HA doesn’t like the configuration: expected a dictionary for dictionary value @ data['action'][0]['data_template']. Got None.

How do I turn that JSON map to a dictionary?

Try:

- alias: Control switches via MQTT
  trigger:
    platform: mqtt
    topic: homeassistant/to-ha/cmd
  action:
    - service_template: "{{ trigger.payload_json.service }}"
      data_template:
        entity_id: "{{ trigger.payload_json.data.entity_id }}"

Yes, that works. I’ve tried it. But I want to be able to use the same automation rule with different services and they use different attributes of data.

E.g. set a value of an input_number.

Oh, I see. Unfortunately a template can only result in a string, it can’t result in a dictionary.

OK! Thanks for making that clear! Then I’ll go with the approach of adding different automation rules for switches, dimmable lamps, inputs and so on.