Under: Home Assistant > Developer Tools > Templates, given a JSON I want to to edit a value and add a new key/value pair.
{% set temp = {'a': '1', 'b': 2} %}
{{ temp }}
Print:
{'a': '1', 'b': 2}
I have no idea how to add a key/value pair, unfortunately I didn't find anything, and I would like a solution without looping the elements to create a new json or similar, if it exists I would like a "combine" or "merge" command, otherwise I totally change my way (for example a string).
Regarding the modification of a value (subject to the first request) I can print the value of a
in two ways:
{{ temp.a }}
{{ temp['a'] }}
Print:
1 1
However, I cannot assign a new value to it:
{% set temp.a = '2' %}
Gives the error:
TemplateRuntimeError: cannot assign attribute on non-namespace object
{% set temp['a'] = '2' %}
Gives the error:
TemplateSyntaxError: expected token 'end of statement block', got '['
UPDATE WITH ANSWER
Thanks to @β.εηοιτ.βε for pointing me to the correct answer.
{% set temp = {'a': '1', 'b': 2} %}
{{ temp }}
---
{% set temp = dict(temp, **{'c': '3'}) %}
{{- temp }}
---
{% set temp = dict(temp, **{'c': 4}) %}
{{- temp }}
This code produce this result:
{'a': '1', 'b': 2}
---
{'a': '1', 'b': 2, 'c': '3'}
---
{'a': '1', 'b': 2, 'c': 4}