MQTT sensors value template weirdness

Hi All,

I’ve got some strange behaviour happening with MQTT template sensors; sometimes they work and sometimes they don’t, yet the JSON data being sent is always the same format.

Here’s one example…
Error when it doesn’t work:

2023-04-14 15:20:01.253 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'value_json' is undefined when rendering '{{ 100 - (value_json.nvme0_wear | int ) }}'

JSON payload from that instance:

{ "nvme0_wear": 98, "nvme0_temp": 39 }

Sensor definition block:

  sensor:
    - name: "Tobermory NVME0"
      unique_id: "tobermory_nvme0temp"
      state_topic: "systems/tobermory"
      suggested_display_precision: 0
      unit_of_measurement: "C"
      value_template: "{{ value_json.nvme0_temp | int }}"
    - name: "Tobermory NVME0 wear"
      unique_id: "tobermory_nvme0wear"
      state_topic: "systems/tobermory"
      suggested_display_precision: 0
      unit_of_measurement: "%"
      value_template: "{{ 100 - (value_json.nvme0_wear | int ) }}"

Any ideas why it sometimes updates the value and sometimes throws that error? I’ve had MQTT explorer watching the traffic for a couple of hours (these sensors report every 10 minutes) and the JSON payload looks identical each time, yet only twice in those 2 hours did it appear to update the sensor history!

For this sensor, the temperature part seems to work, but I have others with the same definition where it throws the ‘value_json is undefined’ error for the temperature.

Thanks!