Use json in a variable

I want to use thermostat modes based on input helpers in an automation based on JSON.
How can I efficyently loop through the different modes and get either the value or mode name from Yaml in my automation.
This is my json data:

[{
		"mode": "Eco",
		"temp": 19.0
	},
	{
		"mode": "Comfort",
		"temp": 20.0
	},
	{
		"mode": "Spaarstand",
		"temp": 17.0
	},
	{
		"mode": "Uit",
		"temp": 10
	}
]

Automation would be something like:

- id: '123456789'
  alias: thermostat_modes_example
  variables:
    thermostat_modes: '[ 
      { "mode":"Eco", "temp":19.0 },
      { "mode":"Comfort", "temp": 20.0 },
      { "mode":"Spaarstand", "temp":17.0 },
      { "mode":"Uit", "temp":10} 
      ]'
  trigger:
    - platform: state
      entity_id:
        - climate.radiator
      attribute: temperature
  condition: []
  action:
    - service: input_number.set_value
      data_template:
        entity_id: input_number.temperature
        value: 
          {% for thismode in thermostat_modes.mode %}
          {% if thismode == states("input_select.thermostatmode") %}
            {{ thismode.temp }}
          {% endif %}
        {%  endfor %}

Define the value of thermost_modes as a list of dictionaries in YAML format (it’s more concise than in JSON format). Then use the selectattr filter to extract the desired value.

- id: '123456789'
  alias: thermostat_modes_example
  variables:
    thermostat_modes:
      -  mode: Eco
         temp: 19
      -  mode: Comfort 
         temp: 20
      -  mode: Spaarstand 
         temp: 17
      -  mode: Uit 
         temp: 10
  trigger:
    - platform: state
      entity_id:
        - climate.radiator
      attribute: temperature
  condition: []
  action:
    - service: input_number.set_value
      target:
        entity_id: input_number.temperature
      data:
        value: >
          {{ thermostat_modes
            | selectattr('mode', 'eq', states('input_select.thermostatmode'))
            | map(attribute='temp')
            | list | first | default(19) }}

NOTE

The final default(19) will report 19 in case the template cannot find a matching value (i.e. the input_select’s value cannot be found in thermostat_modes).

1 Like

Thanx for your quick reply. I will investigate this!