Json attributes template for mqtt sensor?

'Ello,

Quick question : I have a sensor sending values through mqtt to HA. Here’s an example payload :
Topic : random/confidential

{"DeviceId":"Meter 3","Time":"2025-01-06 02:47:41","D31":"58318.84","created_at":"2025-01-06 02:47:42"}

In HA’s config file I created a sensor like so :

mqtt:
  sensor:
    - name: "Meter 3"
      expire_after: 55
      unique_id: 3
      state_topic: "random/confidential"
      value_template: "{{value_json.D31}}"
      json_attributes_topic: "random/confidential"
      json_attributes_template: //not sure

I’m able to see D31 values no problem - but I also want to create 2 additional attributes : DeviceId (named as “Meter no.”) and Time (named as “EST”) to show as attributes of the Meter 3 entity.

I’m not sure how to use the “json_attributes_template” command for this.

I tried this :

mqtt:
  sensor:
    - name: "Meter 3"
      expire_after: 55
      unique_id: 3
      state_topic: "random/confidential"
      value_template: "{{value_json.D31}}"
      json_attributes_topic: "random/confidential"
      json_attributes_template: >
        {"Meter no." : {{value_json.DeviceId}},
          "EST" : {{value_json.Time}}}

But that did nothing - I can still see D31 values but not those other attributes (DeviceId and Time) in the entity card.

Thanks.

The values are strings so they should be delimited by quotation marks, otherwise they’re assumed to be numeric.

json_attributes_template: >
  {"Meter no": "{{value_json.DeviceId}}", "EST": "{{value_json.Time}}" }
1 Like

Ok this worked but the attributes’ names default to those in the payload ie. it’s not “Meter no.” or “EST”, it is instead “DeviceId” and “Time”.

The default behavior of json_attributes_topic is to create attributes based on the key names found in the JSON payload.

The json_attributes_template option allows you to manipulate the JSON payload to affect the attributes that are produced, such as select specific keys, rename keys, change values, etc.

Based on the behavior you described, it sounds like it’s ignoring the json_attributes_template option.

Hey actually nevermind - this worked :+1:

I didn’t wait long enough for the value to update the first time to see the change :face_with_head_bandage:

1 Like