Creating sensor + split attribute output

Hi there.
I have custom weather integration.
This integration has many sensors, one of them is today forecast.
This sensor have many attributes:

minimum_temperature: 
value: '10'
unit: °C

maximum_temperature: 
value: '22'
unit: °C

uvi: 
value: '6'
unit: uv

weather : 
value: Clear
icon: mdi:weather-sunny

description: 
value: >
  This evening and tonight: Mostly clear. Towards early morning strong easterly
  winds will prevail in the northern mountains.

date: 
value: 2023/03/10

20:00: 
weather:
  value: Clear
  icon: mdi:weather-sunny
temperature:
  value: 18
  unit: °C

friendly_name: today

I want to create a new sensor with value of description in it’s state.
To do this, I’m trying to use template developer tools to get correct output:

{{ (state_attr('sensor.ims_forecast_today', 'description') | string )}}

But getting some unnecessary items at the beginning and at the end of output:

{
  "value": "This evening and tonight: Mostly clear. Towards early morning strong easterly winds will prevail in the northern mountains.\n"
}

How can I exclude unnecessary symbols from this output?

Maybe this will help you

Need to be careful using “dot notation” with keys that also have special meanings in Python or Jinja. Probably safest with bracket notation: this should work:

{{ (state_attr('sensor.ims_forecast_today', 'description')['value'] )}}

Thanks and care to expand on this? is it because of ‘value’ in particular, i.e. if it would have been (say) ‘duck’ it would not be an issue?

Exactly. In this instance, I think you’d get away with it, but pop this in the template editor to see the issue:

{% set a = {'duck':'quack','value':'careful','keys':'ouch','0':'nodots'} %}
{{ a.keys }}
{{ a['keys'] }}
{{ a.value }}
{{ a['0'] }}

Because keys() is a function on a dictionary, you can’t use dot notation to refer to a member called keys. Same with e.g. a.0 which is interpreted as an index, not valid on a dictionary. It’s always safer to use bracket notation.

1 Like


here is sensor attribute. i need to take a value of description attribute. But it includes word “value” inside. I need it without this word and without any other symbols

issue solved by chatgpt :slight_smile:
{{ state_attr('sensor.ims_forecast_today', 'description')['value'] | regex_replace('\n', '') | regex_replace('^"|"$', '') | replace('Today: ', '') }}

How does its suggestion differ from the solution I gave above?

Put that and the ChatGPT one in the template editor and see if there’s any difference.

The ChatGPT solution you show simply adds a few extra filters to remove newlines, double quote characters at the very beginning or end of the string, and the string "Today: ". You didn’t ask for that processing to be done, and it looks to me like you’re taking its answer without understanding what it’s doing.