MQTT json payload with varying values

Hi - I was wondering if it is possible to create a template that can handle the following

Full payload { “battery”: 75, “temperature”: 20.4, “humidity”: 34 }
Partial payload { “temperature”: 20.8 }

When a normal template, set up for the 3 values in the full payload, receives the partial payload the other values are cleared. I would like to only have the selected values to be updated, and the others to be untouched.

Possible?

- platform: mqtt
    name: "T7x Battery"
    device_class: battery
    unique_id: weather_T7_b
    state_topic: "weather/T7"
    value_template: "{{ value_json.battery }}"  
  - platform: mqtt
    name: "T7x Temp"
    device_class: temperature
    unique_id: weather_T7_t
    state_topic: "weather/T7"
    unit_of_measurement: "°C"
    value_template: "{{ value_json.temperature }}"
  - platform: mqtt
    name: "T7x Humidity"
    device_class: humidity
    unique_id: weather_T7_h
    state_topic: "weather/T7"
    unit_of_measurement: "%"
    value_template: "{{ value_json.humidity }}"

Try the following version.

  - platform: mqtt
    name: "T7x Battery"
    device_class: battery
    unique_id: weather_T7_b
    state_topic: "weather/T7"
    value_template: "{{ value_json.battery if value_json.battery is defined else states('sensor.t7x_battery')}}"
  - platform: mqtt
    name: "T7x Temp"
    device_class: temperature
    unique_id: weather_T7_t
    state_topic: "weather/T7"
    unit_of_measurement: "°C"
    value_template: "{{ value_json.temperature if value_json.temperature is defined else states('sensor.t7x_temp)}}"
  - platform: mqtt
    name: "T7x Humidity"
    device_class: humidity
    unique_id: weather_T7_h
    state_topic: "weather/T7"
    unit_of_measurement: "%"
    value_template: "{{ value_json.humidity if value_json.humidity is defined else states('sensor.t7x_humidity')}}"

If the JSON payload fails to contain the desired key, the template simply reports the sensor’s existing value.

Hi Taras

Thanks a lot for the input. I’ll give that a try soon. I’ll update here once tried (i’m working on another subject right now).