Help with MQTT sensor attribute

i’ve been trying to create an mqtt sensor that populates data from an MQTT topic in an attribute. the sensor is relatively simple:

  sensor:
    - name: "MQTT Persistent Global Variables"
      unique_id: mqtt_persistent_global_variables
      state_topic: "global_variables/mqtt_persistent_global_variables"
      value_template: "{{ value_json.state }}"
      json_attributes_template:  "{{ value_json.vars }}"

the data in MQTT topic looks like this:

{
  "state": "2024-12-16T21:21:23.850702-05:00",
  "vars": {
    "debounce_ac_temp_control": {
      "timestamp": "2024-12-16T16:07:38.245043-05:00",
      "value": 30
    },
    "debounce_tv_backlight_sync": {
      "timestamp": "2024-12-16T16:28:36.324764-05:00",
      "value": 180
    },
    "test1": {
      "timestamp": "2024-12-16T21:13:50.395101-05:00",
      "value": null
    },
    "test123": {
      "timestamp": "2024-12-16T21:18:04.357604-05:00",
      "value": 123
    }
  }
}

i’ve tried every combination i can think of for value_json but none seem to populate the sensor attributes. the only attribute i get is the Friendly Name. Here are some of the combinations that i’ve tried:

  {{ value_json['vars'] }}   
  {{ value_json.vars }}   
  {{ value_json }}   

i saw some people syaing you need to pipe them to_json, so i’ve tried all them with | to_json as well. I also tried with just the value return, with same result. at this point i don’t know what else to try.

I believe that using json_attributes_template also requires you to specify json_attributes_topic (set to the same value as state_topic in your case). I generally don’t bother with the template, because omitting it loads all attributes (except state).

1 Like

So (and using bracket notation instead of dot notation for safety):

sensor:
    - name: "MQTT Persistent Global Variables"
      unique_id: mqtt_persistent_global_variables
      state_topic: "global_variables/mqtt_persistent_global_variables"
      value_template: "{{ value_json['state'] }}"
      json_attributes_topic: "global_variables/mqtt_persistent_global_variables"
      json_attributes_template:  "{{ value_json['vars'] }}"
1 Like

Thank you gents, both these solutions work, i went with @michaelblight 's option since it is less lines. Appreciate the help!