本帖最后由 wupeng 于 2024-12-25 14:40 编辑
各位大佬大家好,最近一直在配置yaml对接MQTT传感器,看了很多官方的文档但是遇到一个困难
在读取简单结构的JSON时,可以直接value_json.XXX 官方的文档如下。
https://www.home-assistant.io/integrations/sensor.mqtt/
{
"ClientName": <string>,
"IP": <string>,
"MAC": <string>,
"RSSI": <string>,</font>
"HostName": <string>,
"ConnectedSSID": <string>
}
使用直接取值的格式:value_json.XXX
# Example configuration.yaml entry
mqtt:
sensor:
- name: "RSSI"
state_topic: "home/sensor1/infojson"
unit_of_measurement: "dBm"
value_template: "{{ value_json.RSSI }}"</font>
availability:
- topic: "home/sensor1/status"
payload_available: "online"
payload_not_available: "offline"
json_attributes_topic: "home/sensor1/attributes"
获取嵌套的JSON时,
{
"Timer1": {
"Arm": <status>,</font>
"Time": <time>
},
"Timer2": {
"Arm": <status>,</font>
"Time": <time>
}
}
使用取值并嵌套的模式:value_json.XXX.XXX
# Example configuration.yaml entry
mqtt:
sensor:
- name: "Timer 1"
state_topic: "tele/sonoff/sensor"
value_template: "{{ value_json.Timer1.Arm }}"</font>
son_attributes_topic: "tele/sonoff/sensor"
json_attributes_template: "{{ value_json.Timer1 | tojson }}"
- name: "Timer 2"
state_topic: "tele/sonoff/sensor"
value_template: "{{ value_json.Timer2.Arm }}"</font>
json_attributes_topic: "tele/sonoff/sensor"
json_attributes_template: "{{ value_json.Timer2 | tojson }}"
但是如果遇到复杂的JSON,多层嵌套并含有数组时,该如何配置文件读取深层嵌套的值
value_template: "{{?????????}}"
例如:如何配置value_template能够取到下列meter数组中嵌套的,两个Uab值。
{
"time": "2024-12-24 14:20:00",
"sequence": "38",
"source": "da",
"meter": [
{
"id": "1",
"status": "1",
"values": {
"Uab": "220.000000",</font>
"Ia": "0.000000",
"P": "0.000000"
}
},
{
"id": "2",
"status": "2",
"name": "VrtDev1",
"values": {
"Uab": "220.000000",</font>
"Ia": "0.000000",
"P": "0.000000"
}
}
]
}
翻阅了很多文档和资料都是针对简单JSON的配置,实在没办法发帖求助。
希望配置过的朋友能够指点迷津。
|