Here’s an example:
This is how you would manually define a sensor that uses json_attributes_template
.
## Designed to receive a payload like this:
## {"used_space": 25, "sys_clock_speed": 1500, "cpu_temp": 43.0, "voltage": 0.8500, "cpu_load": 1.25, "memory": "False", "swap": "False"}
## Demonstrates how to re-map the JSON data's key names to new attribute names
- platform: mqtt
name: "Test Sensor"
state_topic: "test"
value_template: "{{ value_json.cpu_load }}"
json_attributes_topic: "test"
json_attributes_template: >-
{ "used": {{value_json.used_space}},
"speed": {{value_json.sys_clock_speed}},
"temp": {{value_json.cpu_temp}},
"voltage": {{value_json.voltage}},
"memory": "{{value_json.memory}}",
"swap": "{{value_json.swap}}" }
Here’s how you could use a script to define the same sensor via MQTT Discovery. Note how the double-quotes used in json_attributes_template
must be escaped.
#script:
create_test_sensor:
sequence:
- service: mqtt.publish
data:
topic: homeassistant/sensor/test/config
retain: true
payload: >
{
"name": "Test Sensor",
"state_topic": "test",
"value_template": "{{ value_json.cpu_load }}",
"json_attributes_topic": "test",
"json_attributes_template": "{ \"space\": {{value_json.used_space}}, \"speed\": {{value_json.sys_clock_speed}}, \"temp\": {{value_json.cpu_temp}}, \"voltage\": {{value_json.voltage}}, \"memory\": \"{{value_json.memory}}\", \"swap\": \"{{value_json.swap}}\" }"
}
I ran the script, it created sensor.test_sensor
, then I published the sample payload (shown below) and it was successfully received and corresponding attributes were created:
Payload:
{"used_space": 25, "sys_clock_speed": 1500, "cpu_temp": 43.0, "voltage": 0.8500, "cpu_load": 1.25, "memory": "False", "swap": "False"}