How to use a JSON path in a template sensor where the element name starts with a number

Hi,

I’m using openweathermap to read weather data and I’m storing the hourly result from the API in an attribute for further processing.

In my template I can happily dump out the results of the JSON with…

{{ state_attr('sensor.southampton_weather_openweathermap', 'hourly')[0] }}

and that gives me the following JSON

{
  "dt": 1723813200,
  "temp": 22.87,
  "feels_like": 22.52,
  "pressure": 1015,
  "humidity": 50,
  "dew_point": 11.91,
  "uvi": 5.52,
  "clouds": 16,
  "visibility": 10000,
  "wind_speed": 1.86,
  "wind_deg": 241,
  "wind_gust": 2.2,
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    }
  ],
  "rain": {
    "1h": 0.5
  },
  "pop": 0
}

Now I can access every element I want to process, such as cloud as follows…

{{ state_attr('sensor.southampton_weather_openweathermap', 'hourly')[0].clouds }}

and that works, but when I try to access the element for the rain I get a template error that “h” is unexpected.

{{ state_attr('sensor.southampton_weather_openweathermap', 'hourly')[0].rain.1h }}

invalid template (TemplateSyntaxError: expected token ')', got 'h')

Using the template developer tools if I remove the 1 it then thinks it is a valid JSON path, but obviously doesn’t find it.

It seems that if it sees a number after the . in the path it thinks it is an instance value.

How can I declare the path specifying JSON elements starting with a number?

In Devtools > template … paste this and play around

{% set j = {
  "dt": 1723813200,
  "temp": 22.87,
  "feels_like": 22.52,
  "pressure": 1015,
  "humidity": 50,
  "dew_point": 11.91,
  "uvi": 5.52,
  "clouds": 16,
  "visibility": 10000,
  "wind_speed": 1.86,
  "wind_deg": 241,
  "wind_gust": 2.2,
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    }
  ],
  "rain": {
    "1h": 0.5
  },
  "pop": 0
} %}


{{ j.rain['1h'] }}

In this particular situation, use bracket notation (instead of dot notation).

{{ state_attr('sensor.southampton_weather_openweathermap', 'hourly')[0].rain['1h'] }}

Reference

Dot vs Bracket Notation

1 Like

That’s the ticket, I couldn’t find any docs that helped with the notation syntax…cheers

1 Like