0

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}
Baro
  • 5,300
  • 2
  • 17
  • 39
  • 1
    Does this answer your question? [How to add a new entry into a dictionary object while using jinja2?](https://stackoverflow.com/questions/36886650/how-to-add-a-new-entry-into-a-dictionary-object-while-using-jinja2) – β.εηοιτ.βε Mar 08 '23 at 07:58
  • @β.εηοιτ.βε The last answer is the only one that works. Thanks for pointing me to the correct answer, but I wouldn't consider this a duplicate (although maybe technically it is), because context is important. I didn't find it because I was looking specifically for "Home Assistant" which has limitations, and for those looking for the same question in this context it will be easier to find the answer. Obviously it is questionable, but from the point of view of utility to users, I would leave it. – Baro Mar 08 '23 at 14:19

0 Answers0