templatesjinja2home-assistant

Template a JSON in Home Assistant


Under: Home Assistant -> Developer Tools -> Templates

Given a JSON schema, I want to edit a value and add a new key/value pair.

{% set temp = {'a': '1', 'b': 2} %}
{{ temp }}

Output:

{'a': '1', 'b': 2}

I have no idea how to add a key/value pair, unfortunately I didn't find anything that is useful in solving this 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'] }}

Outputs:

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

And similarly, the following:

{% set temp['a'] = '2' %}

Gives the error:

TemplateSyntaxError: expected token 'end of statement block', got '['


Solution

  • Thanks to @β.εηοιτ.βε for pointing out the correct solution:

    {% 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}