I am currently struggling with passing some JSON data I have parsed to a script and then utilising that data for a service call.
Essentially, I am pulling data via the Emby API (via REST commands hard-coded into my configuration.yaml) and storing it in a response variable called json_data.
I am then attempting to use the following code to pull out a specific value from the json data and ideally load it into a input_text helper via the “Wait for Template” block and the following code:
{% for x in json_data.content %}
{% if x.DeviceName == "Living Room" %}
{% set input_text.emby_session_id = x.Id %}
{% endif %}
{% endfor %}
The idea would then to create another REST command that uses the stored variable.
However, when testing this code I get the following:
TemplateRuntimeError: cannot assign attribute on non-namespace object
If I try this code:
{% for x in json_data.content %}
{% if x.DeviceName == "Living Room" %}
{% set DevId = x.Id %}
{% endif %}
{% endfor %}
{{DevId}}
I get this error:
'DevId' is undefined
Can anyone help me with a way to break my data out of loop jail so I may use it for the rest of my script? Many thanks in advance!
A variable assigned a value inside a Jinja2 for-loop doesn’t retain the assigned value outside the loop.
You have to use namespace to define the variable prior to referencing it inside the for-loop.
{% set ns = namespace(DevId = '') %}
{% for x in json_data.content if x.DeviceName == "Living Room" %}
{% set ns.DevId = x.Id %}
{% endfor %}
{{ns.DevId}}
On a separate note, a for can also support an if so your separate if-endif can be merged directly into the for.
There may be a way to replace the entire for-loop with a select statement but I would need to see the structure of the JSON data to confirm it’s feasible.
Thank you for your help! I really appreciate your assistance and feedback on how I can improve my code. I won’t take up more of your time by providing you with enough details for the select statement but might post the code here when I figure it out.
For those following a similar path, I essentially put the above code into the data of a service action to update an input_text helper and this allowed me to store my value in a helper.