Dynamically accessing variables

Hi,

I’d like to create a script that takes an arbitrary entity ID from the MQTT json payload and accesses the entities values. Here is an example. This example is specifically for the TP-Link HS110 switch but if possible I’d like to apply it to several values.

    action:
      - service: mqtt.publish
        data_template:
          topic: 'homeassistant/uplink'
          payload : "{{ states.switch[trigger.payload_json['plugID']]['attributes']['voltage'] | float}}"

This does not pass the check configuration, but replacing the payload line with

          payload : "{{ states.switch['exampleEntityID']]['attributes']['voltage'] | float}}"

does parse.

I’ve tried to create a similar sample in the dev-template test page, I’m hoping the following is accurately replicating whats happening in production (shown above)

{% set trigger = {
  "payload_json": {
  	"plugID" : "exampleEntityID"
   }
} 
%}

{% set states = {
  "switch": { "exampleEntityID" : {"attributes": {"voltage" : 120.1 }} }
} 
%}

{{ trigger.payload_json['plugID'] }}
{{ states.switch[trigger.payload_json['plugID']]['attributes']['voltage'] | float}}
{{ states.switch['exampleEntityID']['attributes']['voltage'] | float}}

outputs

exampleEntityID
120.1
120.1

What syntax am I doing incorrectly? Is there a web page I read up on and check the syntax? I’m guessing this has something to do with the Jinja scripting but I’m unable to find a good example of what I want. Some mention using the format command like so

payload : "{{ states.switch['s' | format(trigger.payload_json['plugID'])]['attributes']['voltage'] | float}}"

That gives mixed/incorrect results.

For anyone looking for a solution, I was able to get something going by changing around ’ and "

payload : '{{ states.switch["%s" | format(trigger.payload_json["plugID"])]["attributes"]["voltage"] | float}}'

If anyone thinks there is a better way to accomplish this I am open to suggestions.

Hmm. I’m not seeing why your original try doesn’t pass the configuration check. But maybe try something like this:

   action:
      - service: mqtt.publish
        data_template:
          topic: 'homeassistant/uplink'
          payload : "{{ state_attr('switch.' ~ trigger.payload_json.plugID, 'voltage') | float }}"