kfdm
(Paul Traylor)
September 19, 2024, 8:39am
1
I’m currently using the json integration for an NFC to Json publisher
- alias: NFC to MQTT
description: Send NFC Scan events to MQTT
trigger:
- platform: event
event_type: tag_scanned
action:
- data:
topic: nfc/{{trigger.event.context.user_id}}/{{ trigger.event.data.tag_id }}
payload: '{{ trigger.event.data }}'
action: mqtt.publish
mode: single
I would like to publish the payload a json payload though currently if I do it inline, I just get a string like
{'tag_id': '8344f092-f6b1-438a-92d3-ce9143013083', 'name': 'tag_name', 'device_id': 'f23a3b4358ef41b5085b798327d26d16'}
It seems like it could be modified to support a json payload to make things easier on users.
async def async_publish_service(call: ServiceCall) -> None:
"""Handle MQTT publish service calls."""
msg_topic: str | None = call.data.get(ATTR_TOPIC)
msg_topic_template: str | None = call.data.get(ATTR_TOPIC_TEMPLATE)
payload: PublishPayloadType = call.data.get(ATTR_PAYLOAD)
evaluate_payload: bool = call.data.get(ATTR_EVALUATE_PAYLOAD, False)
payload_template: str | None = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if msg_topic_template is not None:
# The use of a topic_template in an mqtt publish action call
# has been deprecated with HA Core 2024.8.0
# and will be removed with HA Core 2025.2.0
rendered_topic: Any = MqttCommandTemplate(
template.Template(msg_topic_template, hass),
).async_render()
ir.async_create_issue(
hass,
DOMAIN,
f"topic_template_deprecation_{rendered_topic}",
This file has been truncated. show original
It seems like it would be possible to do something like this to convert the payload automatically
action:
- data:
topic: nfc/{{trigger.event.context.user_id}}/{{ trigger.event.data.tag_id }}
payload:
key1: value1
key2: value2
action: mqtt.publish
if instanceof(dict, payload):
payload = json.dumps(payload)
tom_l
September 19, 2024, 8:41am
2
Sir_Goodenough
((SG) WhatAreWeFixing.Today)
September 19, 2024, 8:41am
3
kfdm
(Paul Traylor)
September 19, 2024, 8:48am
4
Oh, thank you for the reply both of you! Yes, for my specific example that seems to work (just tested it now). Not sure how I missed that (though Home Assistant is a large project )
Though in other cases, if you need to customize the payload shape, a simple to_json
filter likely would not work well, and instead would have to rely on creating a manual json payload and being careful with escaping of quotes.
tom_l
September 19, 2024, 8:56am
5
You can also put lists in there.
petro
(Petro)
September 19, 2024, 12:01pm
6
kfdm:
Though in other cases, if you need to customize the payload shape, a simple to_json
filter likely would not work well, and instead would have to rely on creating a manual json payload and being careful with escaping of quotes.
The whole point of to_json
is for it to escape your json regardless of the shape. I think you have a miss conception on how it works.