Creating RESTful sensor, but keep getting 'value_json' is undefined

Trying to create a sensor of the current water level in a local river. I got the following from ChatGPT:

sensor:
  - platform: rest
    name: Mohawk River Stage (NOAA)
    resource: https://api.water.noaa.gov/nwps/v1/gauges/SPRO3/stageflow
    method: GET
    headers:
      Accept: application/json
    value_template: >
      {% set obs = value_json.data.observed %}
      {{ (obs[-1].stage) if obs }}
    unit_of_measurement: 'ft'
    device_class: water
    icon: mdi:river
    scan_interval: 900

I"ve tried several variations, but keep getting ‘value_json’ is undefined in the template editor. Any idea what I’m doing wrong?

Two things with your value_template.

  1. Should be value_json.observed.data.
  2. .stage does not exist on the data objects. There is .primary and .secondary. I note that the observation header has information in primaryName and secondaryName. Do you exoect these to ever change. If not just use .primary

Note, you won’t get value_json in template editor. It is special to internals of Home Assistant template engine when an integration passes json, like REST. I test by mocking up an extra line or two. e.g.

{# mock data #}
{% set json = '{
  "observed":  {
    "pedts":  "HGIRG",
    "issuedTime":  "2025-06-29T20:45:00Z",
    "wfo":  "PQR",
    "timeZone":  "PST8PDT",
    "primaryName":  "Stage",
    "primaryUnits":  "ft",
    "secondaryName":  "Flow",
    "secondaryUnits":  "kcfs",
    "data":  [
      {
        "validTime":  "2025-05-30T21:45:00Z",
        "generatedTime":  "2025-05-30T22:10:59Z",
        "primary":  1.43,
        "secondary":  0.11
      }]
    }}' %}
{% set value_json = json | from_json %}
{# rest value_template testing #}
{% set obs = value_json.observed.data %}
{{ (obs[-1].primary) if obs }}
1 Like

The code you shared goes into your configuration.yaml file. The template editor is used to test out Jinja templates. Templates are the code that is surrounded by curly brackets.

Thanks a lot. I’ve got a lot to learn.

1 Like

Thanks. I’ve got a lot to learn.