Template variable warning: 'value_json' is undefined when rendering

Hello :slight_smile:
Im trying to create a new sensor to home assistant that its value is based on the response of a webhook provided by an external service.
The service returns an empty response in most cases but some json with a valid json with a data field - array of items - in some cases.
An example response json looks like this:

{
  "id": "133284777020000000",
  "cat": "1",
  "title": "讬专讬 专拽讟讜转 讜讟讬诇讬诐",
  "data": [
    "转拽讜诪讛",
    "谞转讬讘讜转"
  ],
  "desc": "讛讬讻谞住讜 诇诪专讞讘 讛诪讜讙谉 讜砖讛讜 讘讜 10 讚拽讜转"
}

My configuration looks like this:

rest:
  - resource: https://www.oref.org.il/WarningMessages/alert/alerts.json
    scan_interval: 2
    sensor:
      - name: oref_alerts
        value_template: "{{ value_json['data'] if value_json else [] }}"
    headers:
      Accept: application/json
      Content-Type: application/json
      x-requested-with: XMLHttpRequest
      Referer: https://www.oref.org.il//12481-he/Pakar.aspx

The endpoint and headers work correctly, but in both cases (no empty response and json response) I get the following warning in the log:

Template variable warning: 'value_json' is undefined when rendering

and the value of the sensor is always the fallback: []
Any ideas?

Try this:

value_template: "{{ value_json.data | float(0) if value_json.data else 0 }}"

Use is defined to confirm value_json exists.

        value_template: "{{ value_json['data'] if value_json is defined else [] }}"

You can be extra cautious and confirm value_json is defined as well as value_json['data'].

        value_template: "{{ value_json['data'] if value_json is defined and value_json['data'] is defined else [] }}"

I found the issue but not sure how to solve it elegantly within the sensor definition. The first char of that json is some whitespace. Trimming the value before parsing it solves all the issue. but how do I handle it within the configuration file?