MQTT sensor with changing fields

I have created the following MQTT Sensor:

 - platform: mqtt
   name: "Meter Power"
   state_topic: "power/#"
   qos: 0
   unit_of_measurement: "W"
   value_template: "{{value_json.power }}"

below are some example values I am receiving. What would be the correct way to parse them?

{"time": 1575888977.0, "power": 195.0}
{"time": 1575888984.0, "power": 199.0}
{"time": 1575631237.0, "price": 0.0, "tier": 0}
{"time": 1575888992.0, "power": 199.0}
{"time": 1575889000.0, "power": 197.0}

The sensor is updated but sometimes is empty (I guess when power is not one of the keys in the sensor data.

What do you want the sensor to show? The power? Do you just want to show 0 instead of an empty field in case there is now power reading?

I am only really interested in the time and the power usage. (I probably dont even need the time)

Then your code is correct. Do you just want to show 0 instead of an empty field or what is your issue?

If the payload contains power this template will report it as the sensor’s new state otherwise it will report the sensor’s existing state.

 - platform: mqtt
   name: "Meter Power"
   state_topic: "power/#"
   qos: 0
   unit_of_measurement: "W"
   value_template: >
     {{ value_json.power if value_json.power is defined else states('sensor.meter_power') }}
1 Like

Thanks for your help. would like the last value as per Taras solution

Thanks. Thats exactly what I was looking for but just didnt know :slight_smile:

1 Like