Hi all,
I spent quite a bit of time today trying to find a way to use an input_text
entity to store JSON, and then later retrieve, modify and update the JSON key values. This turned out to be way more complicated than I expected due to the limitations of the Jinja2 implementation in HA.
I’m sharing my resulting script in hopes it helps someone else with this process. Note that as of now, this is only capable of handling single level JSON, not multi-level nested data.
alias: Set / Remove Key from input_text JSON
sequence:
- action: input_text.set_value
metadata: {}
data:
value: >-
{% set b = states(text_entity) | from_json %}{% set j = namespace(b={})
%}{% for k in b %}{% if k != key_name %}{% set j.b = dict( j.b, **{
k: b[k] }) %}{% endif %}{% endfor %}{% if key_value is defined %}{%
set j.b = dict( j.b, **{key_name: key_value} ) %}{% endif %}{{ j.b |
to_json }}
target:
entity_id: "{{ text_entity }}"
fields:
text_entity:
selector:
entity: {}
name: Text Entity
description: Entity ID of the input_text helper
required: true
key_name:
selector:
text: null
name: Key Name
description: Name of the key to update or remove
required: true
key_value:
selector:
text: null
name: key_value
description: Value to update to the key, blank to remove the key
description: ""
icon: mdi:code-json
Example usage:
Add / Update a Key
action: script.set_remove_key_from_input_text_json
data:
text_entity: "input_text.my_json_epochs"
key_name: "Key1"
key_value: "{{ as_timestamp(now()) }}"
Remove a Key
action: script.set_remove_key_from_input_text_json
data:
text_entity: "input_text.my_json_epochs"
key_name: "Key1"
To use the JSON values in a template for automation or other scripts:
actions:
- variables:
b: |
{{ states('input_text.my_json_epochs) | from_json }}
- if:
- condition: template
value_template: "{{ 'Key1' in b }}"
then:
- data:
message: "Key1 was set {{ (( as_timestamp(now()) - b['Key1'] ) / 60 )| round(1) }}" minutes ago
notification_id: infonotice
title: "My Title"
continue_on_error: true
action: persistent_notification.create
I’d be eager to get any feedback on how to improve or make this process more efficient!
Thanks!
LK